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

时间:2016-03-12 00:31:25

标签: 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'])

new mycsvfile:

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

我想要的是什么:

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

3 个答案:

答案 0 :(得分:5)

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

writer.writerow([])

我也打开'ab'参数。

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

答案 1 :(得分:2)

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

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

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

#!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,1
0,0,0
0,0,0
0,0,0

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

答案 2 :(得分:0)

搜索(0,2)表示转到文件的结束位置。

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