how to append to a new row when writing to CSV file [duplicate]

百般思念 提交于 2020-12-30 06:14:39

问题


I want to append to a new row in my CSV file when i write to it. Current CSV file look like this:

a,b,c
1,1,1

my code to append to CSV file:

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

What i want:

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

回答1:


With some tinkering I realized you can add the following line to make sure you begin writing on a new line in a csv. Though it seems kind of hackish. Documentation mentions a lot about a kwarg newline='', but it wasn't recognized as valid.

writer.writerow([])

I also open with 'ab' parameter.

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



回答2:


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.




回答3:


seek(0,2) means go to the end position of your file.

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


来源:https://stackoverflow.com/questions/35952254/how-to-append-to-a-new-row-when-writing-to-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!