问题是您的原始文件没有写入最终换行符。这重现了问题:
#!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 的换行符。