将新行附加到旧的csv文件python

问题:将新行附加到旧的csv文件python

我正在尝试在旧的csv文件中添加新行。基本上,每次我运行Python脚本时都会对其进行更新。

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

想知道是否有更好的方法可以做到这一点。

I am trying to add a new row to my old csv file. Basically, it gets updated each time I run the Python script.

Right now I am storing the old csv rows values in a list and then deleting the csv file and creating it again with the new list value.

Wanted to know are there any better ways of doing this.


回答 0

with open('document.csv','a') as fd:
    fd.write(myCsvRow)

使用'a'参数打开文件可以使您追加到文件末尾,而不仅仅是覆盖现有内容。试试看

with open('document.csv','a') as fd:
    fd.write(myCsvRow)

Opening a file with the 'a' parameter allows you to append to the end of the file instead of simply overwriting the existing content. Try that.


回答 1

我更喜欢使用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中的CSVnewline=''正如Natacha所建议的那样,添加会导致您在Python 2和3之间向后不兼容

I prefer this solution using the csv module from the standard library and the with statement to avoid leaving the file open.

The key point is using 'a' for appending when you open the file.

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

If you are using Python 2.7 you may experience superfluous new lines in Windows. You can try to avoid them using 'ab' instead of 'a' this will, however, cause you TypeError: a bytes-like object is required, not ‘str’ in python and CSV in Python 3.6. Adding the newline='', as Natacha suggests, will cause you a backward incompatibility between Python 2 and 3.


回答 2

基于@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'})

我没有和普通作家一起尝试(没有Dict),但我认为也可以。

Based in the answer of @G M and paying attention to the @John La Rooy’s warning, I was able to append a new row opening the file in 'a'mode.

Even in windows, in order to avoid the newline problem, you must declare it as newline=''.

Now you can open the file in 'a'mode (without the 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'})

I didn’t try with the regular writer (without the Dict), but I think that it’ll be ok too.


回答 3

您是否以“ a”模式而不是“ w”模式打开文件?

请参阅python文档中的读写文件

7.2。读写文件

open()返回一个文件对象,并且最常与两个参数一起使用:open(filename,mode)。

>>> f = open('workfile', 'w')
>>> print f <open file 'workfile', mode 'w' at 80a0960>

第一个参数是包含文件名的字符串。第二个参数是另一个包含一些字符的字符串,这些字符描述了文件的使用方式。当仅读取文件时,模式可以为“ r”,仅用于写入时为“ w”(具有相同名称的现有文件将被删除),并且“ a”打开文件以进行追加;写入文件的所有数据都会自动添加到末尾。“ r +”打开文件以供读取和写入。mode参数是可选的;如果省略,则假定为“ r”。

在Windows上,附加到模式的’b’以二进制模式打开文件,因此也有’rb’,’wb’和’r + b’之类的模式。Windows上的Python区分文本文件和二进制文件。读取或写入数据时,文本文件中的行尾字符会自动更改。这种对文件数据的幕后修改对于ASCII文本文件来说是很好的选择,但它会破坏JPEG或EXE文件中的二进制数据。读写此类文件时,请务必小心使用二进制模式。在Unix上,将’b’附加到该模式并没有什么坏处,因此您可以在平台上独立地将其用于所有二进制文件。

Are you opening the file with mode of ‘a’ instead of ‘w’?

See Reading and Writing Files in the python docs

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.


回答 4

如果文件存在并且包含数据,则可以自动生成fieldname参数csv.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)

If the file exists and contains data, then it is possible to generate the fieldname parameter for csv.DictWriter automatically:

# 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)

回答 5

# 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) 
# 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) 

回答 6

我使用这种方式在.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")

I follow this way to append a new line in a .csv file:

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")