如果行存在,如何更新 CSV 文件的列,否则如何使用临时文件附加到同一个 CSV

How to update columns of a CSV file if row exists, else how to append to same CSV, using temporary file

我一直在尝试使用 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 文件中追加一个新行,而不会弄乱 header,同时还在使用临时文件? 由于我上面定义的 tempfile 使用模式 'w',我是否需要创建另一个允许模式 'a' 的临时文件以便追加行?

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

注意:我不知道原始数据的样子,所以您可能需要做一些调整才能让它工作,请随时在评论中询问我更多关于解决方案的信息。

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)

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