如何附加到现有的csv字典或使用python csv添加行?
我使用PRAW获取信息,将一般信息写入csv。当我运行代码来追加数据时,它不会追加现有信息,只是为同一提交添加一行新行,即使它应该检查重复的id如何附加到现有的csv字典或使用python csv添加行?,python,csv,praw,Python,Csv,Praw,我使用PRAW获取信息,将一般信息写入csv。当我运行代码来追加数据时,它不会追加现有信息,只是为同一提交添加一行新行,即使它应该检查重复的id with open('dummycsv.csv', 'r+', newline= '') as f: fieldnames = ['ID', 'Subreddit', 'Karma'] thewriter = csv.DictWriter(f, fieldnames) thewriter.writeheader() re
with open('dummycsv.csv', 'r+', newline= '') as f:
fieldnames = ['ID', 'Subreddit', 'Karma']
thewriter = csv.DictWriter(f, fieldnames)
thewriter.writeheader()
reader = csv.DictReader(f, delimiter=',')
for row in reader: #opens flie for later reading
iden = row['ID']
sub = row['Subreddit'] #assigns names for the columns for comparisons
score = row['Karma']
for submission in reddit.subreddit('all').hot(limit=5): #begin going through reddit via PRAW
if iden == submission.id: #if id is already in file, updates the score of the post
thewriter.write("{},{},{}".format(iden, sub, submission.score))
else: #if a new post, writes a complete row
thewriter.writerow({'ID' : submission.id, 'Subreddit': submission.subreddit, 'Karma':submission.score})
您正在尝试修改已写入文件的内容吗?是的,如果id已存在,请修改其中一个字段,否则请添加新行我认为使用
DictReader
无法修改。我认为它总是附加到文件中。您可以先将所有数据保存在列表中,修改列表中的值,然后在最后使用writerows
方法将所有数据一次性写入文件。