简体   繁体   English

在Python 3.x中将多个字典写入多个csv文件

[英]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. 应将每个字典写入单独的.csv文件中。 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: 最后我想有四个.csv文件看起来像这样:

File1: 文件1:

A,a
B,b

File2: 文件2:

C,c
D,d

File3: ... 文件3:...

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. 变量a,b,c,d,e,f,g,h都是未定义的。
  3. The argument that you pass into csv.writer() must have have write() functionality - in your case it should be a File object. 传递给csv.writer()的参数必须具有write()功能 - 在您的情况下,它应该是File对象。 Hence you should use csv.writer(csvfile) , not csv.writer(eachfilename) . 因此,您应该使用csv.writer(csvfile) ,而不是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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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