简体   繁体   中英

Writing multiple dictionaries to multiple csv files in Python 3.x

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.

  1. Variable names cannot be integers
  2. Variables a, b, c, d, e, f, g, h are all undefined.
  3. The argument that you pass into 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM