Python 如何在写入CSV文件时追加到新行

Python 如何在写入CSV文件时追加到新行,python,csv,Python,Csv,我想在写入CSV文件时附加到该文件的新行。 当前CSV文件如下所示: a,b,c 1,1,1 要附加到CSV文件的我的代码: with open('mycsvfile.csv','a') as f: writer=csv.writer(f) writer.writerow(['0','0','0']) 新的mycsvfile: a,b,c 1,1,1,0,0,0 我想要的是: a,b,c 1,1,1 0,0,0 通过一些修补,我意识到您可以添加以下行,以确保您开始在csv

我想在写入CSV文件时附加到该文件的新行。 当前CSV文件如下所示:

a,b,c
1,1,1
要附加到CSV文件的我的代码:

with open('mycsvfile.csv','a') as f:
    writer=csv.writer(f)
    writer.writerow(['0','0','0'])
新的mycsvfile:

a,b,c
1,1,1,0,0,0
我想要的是:

a,b,c
1,1,1
0,0,0

通过一些修补,我意识到您可以添加以下行,以确保您开始在csv中的新行上写作。虽然这看起来有点老土。文档中提到了很多关于kwarg换行符=''的内容,但没有被认为是有效的

writer.writerow([])
我也用'ab'参数打开

import csv
with open('mycsvfile.csv','ab') as f:
    writer=csv.writer(f)
    writer.writerow([])
    writer.writerow(['0','0','0'])
查找(0,2)表示转到文件的结束位置

writer = open('mycsvfile.csv','a')
writer.seek(0,2)
writer.writelines("\r")
writer.writelines( (',').join(['0','0','0']))

问题是您的原始文件没有写入最后的换行符。这再现了问题:

#!python3
import csv

#initial content
with open('mycsvfile.csv','w') as f:
    f.write('a,b,c\n1,1,1') # NO TRAILING NEWLINE

with open('mycsvfile.csv','a',newline='') as f:
    writer=csv.writer(f)
    writer.writerow([0,0,0])
    writer.writerow([0,0,0])
    writer.writerow([0,0,0])

with open('mycsvfile.csv') as f:
    print(f.read())
输出:

a,b,c
1,1,10,0,0
0,0,0
0,0,0
a,b,c
1,1,1
0,0,0
0,0,0
0,0,0
只需确保正确生成了原始文件:

#!python3
import csv

#initial content
with open('mycsvfile.csv','w') as f:
    f.write('a,b,c\n1,1,1\n') # TRAILING NEWLINE

with open('mycsvfile.csv','a',newline='') as f:
    writer=csv.writer(f)
    writer.writerow([0,0,0])
    writer.writerow([0,0,0])
    writer.writerow([0,0,0])

with open('mycsvfile.csv') as f:
    print(f.read())
输出:

a,b,c
1,1,10,0,0
0,0,0
0,0,0
a,b,c
1,1,1
0,0,0
0,0,0
0,0,0

您可以进行一些黑客操作,以查找文件的结尾并决定写入额外的换行符,但最好修复现有的文件生成,使其始终写入换行符。最简单的方法是从一开始就使用
csv
模块,因为它总是会添加一个带有
writerow

的换行符。如果您运行代码两次并尝试写两行,则会出现问题。将创建更多的空行。@云和为什么?如果用循环添加多个新行,则不需要在该循环中包含空白列表。如果您手动添加另一个writerow,它仍然可以正常工作,不会产生空行。我的意思是,如果只运行代码两次或更多次,而不修改任何内容,将创建空行。哦,是的,因为writerow方法添加了一行,所以在第二次运行时不需要新行。不需要在第二+运行的空白写入器列表。似乎该方法旨在让CSV以新行结束。只是一个提示。如果使用jxn中的原始代码创建一个新的csv文件并附加到该文件中,那么它可以正常工作。JNX的问题是,当他们打开文件以追加
['0','0','0']
时,文件末尾缺少一个新行字符。