我试图添加一个新行到我的旧CSV文件。基本上,每次运行Python脚本时它都会更新。
现在,我将旧的CSV行值存储在一个列表中,然后删除CSV文件,并再次使用新的列表值创建它。
我想知道有没有更好的方法。
我试图添加一个新行到我的旧CSV文件。基本上,每次运行Python脚本时它都会更新。
现在,我将旧的CSV行值存储在一个列表中,然后删除CSV文件,并再次使用新的列表值创建它。
我想知道有没有更好的方法。
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之间的向后不兼容。
# 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)
基于@ 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'})
我没有尝试使用普通的写作者(没有字典),但我认为它也可以。
如果文件存在并且包含数据,那么可以为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'是追加模式。
如果你使用pandas,你可以用这种方式将你的数据帧附加到一个现有的CSV文件中:
df.to_csv('log.csv', mode='a', index=False, header=False)
使用mode='a',我们确保我们附加,而不是覆盖;使用header=False,我们确保我们只附加df行的值,而不是header +值。