I have been struggling with this for a while now, maybe someone can help. I have a list of dictionaries. Each of these dictionaries should be written to a separate .csv file. How do I do this?
What I have so far, which does not work:
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()
In the end I would like to have four .csv files looking like this:
File1:
A,a
B,b
File2:
C,c
D,d
File3: ...
You have several issues with your code that you need to resolve first.
csv.writer()
must have have write()
functionality - in your case it should be a File object. Hence you should use csv.writer(csvfile)
, not csv.writer(eachfilename)
. You cannot assign a dictionary to an integer value. Try this:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.