Python – Write multiple dictionaries to multiple csv files in Python 3.x

Write multiple dictionaries to multiple csv files in Python 3.x… here is a solution to the problem.

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

I’ve been struggling with this for a while, maybe someone can help.
I have a list of dictionaries. Each of these dictionaries should be written to a separate .csv file. What should I do?

What I have so far is not working :

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()

Finally I want four .csv files as follows:

File 1:

A,a
B,b

File 2:

C,c
D,d

File 3: ….

Solution

There are several issues with your code that need to be addressed first.

  1. Variable names cannot be integers
  2. The variables a, b, c, d, e, f, g, h are all undefined.
  3. The argument you pass to csv.writer() must have the write() function – in your case, it should be a File object. Therefore, you should use csv.writer(csvfile) instead of csv.writer(eachfilename).

Related Problems and Solutions