The problem is your original file didn't have a final newline written to it. this reproduces the problem:
#!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())
Output:
a,b,c
1,1,10,0,0
0,0,0
0,0,0
Just make sure the original file was generated properly:
#!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())
Output:
a,b,c
1,1,1
0,0,0
0,0,0
0,0,0
You can do some hack to seek to the end of the file and decide to write the extra newline, but better to fix the existing file generation so it always writes newlines. The easiest way to do that is use the csv
module from the start, since it will always add a newline with writerow
.