[英]Writing rows in a csv using dictionaries in a loop (python 3)
I´m writing on a csv file by adding each row in a loop and using dictionaries. 我正在通过在循环中添加每一行并使用字典来编写csv文件。 The following is the code:
以下是代码:
fieldnames = ['id', 'variable1', 'variable2']
f = open('file.csv', 'w')
my_writer = csv.DictWriter(f, fieldnames)
my_writer.writeheader()
f.close()
for i in something:
something where I get data for mydict
with open('file.csv', 'a+b') as f:
header = next(csv.reader(f))
dict_writer = csv.DictWriter(f, header)
dict_writer.writerow(mydict)
I was sure this code worked for me some years ago but probably I was using python2. 我确定几年前这段代码对我有用,但可能我在使用python2。 Now I´m using python 3 and it shows the following error:
现在我正在使用python 3,它显示以下错误:
header = next(csv.reader(f))
StopIteration
What may be the problem? 可能是什么问题? Thanks
谢谢
My solution was: 我的解决方案是:
fieldnames = ['id', 'variable1', 'variable2']
f= open('file.csv', 'w', newline='')
my_writer = csv.DictWriter(f, fieldnames)
my_writer.writeheader()
for i in something:
something where I get data for mydict
writer.writerow(mydict)
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.