【发布时间】:2020-10-25 07:43:36
【问题描述】:
我一直在尝试使用 CSV 文件构建数据库。
我正在使用符号输入(股票市场代码),并且我能够为每个符号生成与公司网站相对应的网站链接。 我想将该数据库保存到名为 BiotechDatabase.csv 的 CSV 文件中
每次在 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