【问题标题】:How to update columns of a CSV file if row exists, else how to append to same CSV, using temporary file如果行存在,如何更新 CSV 文件的列,否则如何使用临时文件附加到相同的 CSV
【发布时间】:2020-10-25 07:43:36
【问题描述】:

我一直在尝试使用 CSV 文件构建数据库。

我正在使用符号输入(股票市场代码),并且我能够为每个符号生成与公司网站相对应的网站链接。 我想将该数据库保存到名为 BiotechDatabase.csv 的 CSV 文件中

The Database look

每次在 Python 中输入新符号时,我都想验证 CSV 文件的第一列以查看该符号是否存在。如果是这样,我需要覆盖 Web 列以确保它已更新。

如果符号不存在,则需要附加一行包含符号和 Web。

由于将来我需要扩展列以添加更多信息,因此我需要使用 DictWriter,因为某些列可能缺少信息并且需要跳过。 如果符号在数据库中,我已经能够使用以下代码更新符号的信息:

from csv import DictWriter
import shutil
import csv

#Replacing the symbol below with the any stock symbol I want to get the website for
symbol = 'PAVM'

#running the code web(symbol) generates the website I need for PAVM and that is http://www.pavmed.com which I converted to a string below
web(symbol)


filename = 'BiotechDatabase.csv'
tempfile = NamedTemporaryFile('w', newline='', delete=False)

fields = ['symbol','Web']

#I was able to replace any symbol row using the code below:
with open(filename, 'r', newline='') as csvfile, tempfile:
    reader = csv.DictReader(csvfile, fieldnames=fields)
    writer = csv.DictWriter(tempfile, fieldnames=fields)
    for row in reader:   
        if row['symbol'] == symbol:
            print('adding row', row['symbol'])
            row['symbol'], row['Web']= symbol, str(web(symbol))  
        row = {'symbol': row['symbol'], 'Web': row['Web']} 
        writer.writerow(row)
shutil.move(tempfile.name, filename)

如果我在 Python 中输入的符号在 CSV 文件中不存在,我如何在列表底部的 CSV 文件中追加一个新行,而不弄乱标题,同时仍然使用临时文件? 由于我上面定义的tempfile 使用模式'w',我是否需要创建另一个允许模式'a' 的临时文件才能追加行?

【问题讨论】:

    标签: python database csv append writer


    【解决方案1】:

    您可以使用Pandas python 库大大简化您的代码。

    注意:我不知道原始数据的样子,因此您可能需要进行一些调整才能使其正常工作,请随时向我询问有关 cmets 解决方案的更多信息。

    import pandas as pd
    
    symbol = 'PAVM'
    web(symbol)
    
    filename = 'BiotechDatabase.csv'
    fields = ['symbol', 'Web']
    
    # Reading csv from file with names as fields
    df = pd.read_csv(filename, names=fields)
    # Pandas uses the first column automatically as index
    df.loc[symbol, 'Web'] = web(symbol)
    # Saving back to filename and overwrites it - Be careful!
    pd.to_csv(filename)
    

    可能有一些更快的方法可以做到这一点,但这个非常优雅。

    【讨论】:

    • 感谢您的帮助:我做了一些改动,所以标题没有被删除,索引显示正确:很整洁,我担心的是数据库会有更多的列,并且每次我添加一个新列时,我都必须返回到提供给数据库的每个查询函数,并将列添加到上面定义的字段部分。有什么办法可以避免这种麻烦? df = pd.read_csv(filename, names=fields, header=0, index_col='symbol')
    猜你喜欢
    • 2019-12-15
    • 2018-05-24
    • 1970-01-01
    • 2017-07-28
    • 2014-01-27
    • 2016-06-27
    • 1970-01-01
    • 2017-06-30
    • 2018-05-16
    相关资源
    最近更新 更多