我试图添加一个新行到我的旧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)

其他回答

我使用以下方法在.csv文件中添加新行:

pose_x = 1 
pose_y = 2

with open('path-to-your-csv-file.csv', mode='a') as file_:
    file_.write("{},{}".format(pose_x, pose_y))
    file_.write("\n")  # Next line.

【注意】:

Mode ='a'是追加模式。

如果文件存在并且包含数据,那么可以为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'参数打开文件允许您在文件末尾追加内容,而不是简单地覆盖现有内容。试试。

你打开文件的模式是“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模块和with语句来避免打开文件的解决方案。

关键是在打开文件时使用“a”作为追加。

import csv   
fields=['first','second','third']
with open(r'name', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(fields)

如果你使用的是Python 2.7,你可能会在Windows中遇到多余的新行。您可以尝试使用'ab'而不是'a'来避免它们,但这会导致TypeError:需要一个字节类对象,而不是python中的'str'和python 3.6中的CSV。正如Natacha所建议的那样,添加换行符= "将导致Python 2和3之间的向后不兼容。