将新行追加到旧csv文件python

2024-03-28 23:34:32 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答
with open('document.csv','a') as fd:
    fd.write(myCsvRow)

使用'a'参数打开一个文件,您可以将其附加到文件的末尾,而不是简单地覆盖现有内容。试试看。

我更喜欢使用标准库中的^{}模块和^{}语句来避免文件处于打开状态。

关键是在打开文件时使用'a'进行追加。

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

如果您使用的是Python2.7,那么在Windows中可能会遇到多余的新行。您可以尝试使用'ab'而不是'a'来避免它们,但是,这将导致您在Python 3.6中使用TypeError: a bytes-like object is required, not 'str' in python and CSV。正如Natacha建议的那样,添加newline=''将导致您a backward incompatibility between Python 2 and 3

根据@G M的回答,并注意@John La Rooy的警告,我可以在'a'模式下添加一个新行来打开文件。

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'})

我没有试着和普通作家(没有口述稿)一起写,但我想也可以。

相关问题 更多 >