我一直在努力解决这个问题,也许有人可以提供帮助。 我有一个词典列表。应将每个字典写入单独的.csv文件中。我该怎么做?
到目前为止,我的工作无效:
from openpyxl import *
from openpyxl.styles import *
import csv
a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
g = 7
h = 8
one = {'A':a,'B':b}
two = {'C':c,'D':d}
three = {'E':e,'F':f}
four = {'G':g,'H':h}
list = [one,two,three,four]
def main():
for eachfilename, eachdict in enumerate(list):
with open(eachfilename, 'w') as csvfile:
writer = csv.writer(csvfile)
for line in eachdict:
writer.writerow(line)
main()
最后,我希望有四个.csv文件,如下所示:
File1中:
A,a
B,b
文件2:
C,c
D,d
File3:...
答案 0 :(得分:2)
您的代码有几个问题需要先解决。
csv.writer()
的论据必须具有write()
功能 - 在您的情况下,它应该是一个File对象。因此,您应该使用csv.writer(csvfile)
,而不是csv.writer(eachfilename)
。答案 1 :(得分:1)
您无法将字典分配给整数值。试试这个:
import csv
s = [{'A':a,'B':b}, {'C':c,'D':d}, {'E':e,'F':f}, {'G':g,'H':h}]
new_data = [["{},{}".format(a, b) for a, b in i.items()] for i in s]
write = csv.writer(open('filename.csv'))
write.writerows(new_data)