Python 写入CSV文件时如何附加到新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35952254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to append to a new row when writing to CSV file
提问by jxn
I want to append to a new row in my CSV file when i write to it. Current CSV file look like this:
我想在写入时附加到我的 CSV 文件中的新行。当前 CSV 文件如下所示:
a,b,c
1,1,1
my code to append to CSV file:
我要附加到 CSV 文件的代码:
with open('mycsvfile.csv','a') as f:
writer=csv.writer(f)
writer.writerow(['0','0','0'])
new mycsvfile:
新的 mycsv 文件:
a,b,c
1,1,1,0,0,0
What i want:
我想要的是:
a,b,c
1,1,1
0,0,0
回答by Chasevanb
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.
通过一些修补,我意识到您可以添加以下行以确保您开始在 csv 中的新行上书写。虽然它看起来有点hackish。文档中提到了很多关于 kwarg newline='' 的内容,但它不被认为是有效的。
writer.writerow([])
I also open with 'ab' parameter.
我也用'ab'参数打开。
import csv
with open('mycsvfile.csv','ab') as f:
writer=csv.writer(f)
writer.writerow([])
writer.writerow(['0','0','0'])
回答by Mark Tolonen
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
.
您可以做一些 hack 来寻找文件的末尾并决定编写额外的换行符,但最好修复现有的文件生成,以便它始终写入换行符。最简单的方法是csv
从一开始就使用模块,因为它总是会添加一个带有writerow
.
回答by Yunhe
seek(0,2)means go to the end position of your file.
seek(0,2)表示转到文件的结束位置。
writer = open('mycsvfile.csv','a')
writer.seek(0,2)
writer.writelines("\r")
writer.writelines( (',').join(['0','0','0']))