Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何附加到现有的csv字典或使用python csv添加行?_Python_Csv_Praw - Fatal编程技术网

如何附加到现有的csv字典或使用python csv添加行?

如何附加到现有的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

我使用PRAW获取信息,将一般信息写入csv。当我运行代码来追加数据时,它不会追加现有信息,只是为同一提交添加一行新行,即使它应该检查重复的id

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
方法将所有数据一次性写入文件。