我试图添加一个新行到我的旧CSV文件。基本上,每次运行Python脚本时它都会更新。

现在,我将旧的CSV行值存储在一个列表中,然后删除CSV文件,并再次使用新的列表值创建它。

我想知道有没有更好的方法。


当前回答

如果文件存在并且包含数据,那么可以为csv生成fieldname参数。DictWriter自动:

# read header automatically
with open(myFile, "r") as f:
    reader = csv.reader(f)
    for header in reader:
        break

# add row to CSV file
with open(myFile, "a", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writerow(myDict)

其他回答

# I like using the codecs opening in a with 
field_names = ['latitude', 'longitude', 'date', 'user', 'text']
with codecs.open(filename,"ab", encoding='utf-8') as logfile:
    logger = csv.DictWriter(logfile, fieldnames=field_names)
    logger.writeheader()

# some more code stuff 

    for video in aList:
        video_result = {}                                     
        video_result['date'] = video['snippet']['publishedAt']
        video_result['user'] = video['id']
        video_result['text'] = video['snippet']['description'].encode('utf8')
        logger.writerow(video_result) 

你打开文件的模式是“a”而不是“w”吗?

请参阅python文档中的读取和写入文件

7.2. Reading and Writing Files open() returns a file object, and is most commonly used with two arguments: open(filename, mode). >>> f = open('workfile', 'w') >>> print f <open file 'workfile', mode 'w' at 80a0960> The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted. On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

如果文件存在并且包含数据,那么可以为csv生成fieldname参数。DictWriter自动:

# read header automatically
with open(myFile, "r") as f:
    reader = csv.reader(f)
    for header in reader:
        break

# add row to CSV file
with open(myFile, "a", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writerow(myDict)
with open('document.csv','a') as fd:
    fd.write(myCsvRow)

使用'a'参数打开文件允许您在文件末尾追加内容,而不是简单地覆盖现有内容。试试。

基于@ gm的回答,并注意@John La Rooy的警告,我能够追加一个以“a”模式打开文件的新行。

即使在windows中,为了避免换行符问题,也必须声明为newline= "。 现在您可以以'a'模式(不带b)打开文件。

import csv

with open(r'names.csv', 'a', newline='') as csvfile:
    fieldnames = ['This','aNew']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writerow({'This':'is', 'aNew':'Row'})

我没有尝试使用普通的写作者(没有字典),但我认为它也可以。