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

jxn*_*jxn 6 python csv

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

a,b,c
1,1,1
Run Code Online (Sandbox Code Playgroud)

我要附加到CSV文件的代码:

with open('mycsvfile.csv','a') as f:
    writer=csv.writer(f)
    writer.writerow(['0','0','0'])
Run Code Online (Sandbox Code Playgroud)

新的mycsvfile:

a,b,c
1,1,1,0,0,0
Run Code Online (Sandbox Code Playgroud)

我想要的是:

a,b,c
1,1,1
0,0,0
Run Code Online (Sandbox Code Playgroud)

Mar*_*nen 8

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

#!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())
Run Code Online (Sandbox Code Playgroud)

输出:

a,b,c
1,1,10,0,0
0,0,0
0,0,0
Run Code Online (Sandbox Code Playgroud)

只需确保正确生成原始文件:

#!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())
Run Code Online (Sandbox Code Playgroud)

输出:

a,b,c
1,1,1
0,0,0
0,0,0
0,0,0
Run Code Online (Sandbox Code Playgroud)

您可以做一些 hack 来寻找文件的末尾并决定编写额外的换行符,但最好修复现有的文件生成,以便它始终写入换行符。最简单的方法是csv从一开始就使用模块,因为它总是会添加一个带有writerow.


小智 6

通过一些修补,我意识到您可以添加以下行,以确保您开始在csv中的新行上进行编写。虽然看起来有点黑。文档中提到了很多有关kwarg newline =''的内容,但并未被认为是有效的。

writer.writerow([])
Run Code Online (Sandbox Code Playgroud)

我也用'ab'参数打开。

import csv
with open('mycsvfile.csv','ab') as f:
    writer=csv.writer(f)
    writer.writerow([])
    writer.writerow(['0','0','0'])
Run Code Online (Sandbox Code Playgroud)