在Python 3.x中将多个字典写入多个csv文件
16lz
2021-01-22
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?
我一直在努力解决这个问题,也许有人可以提供帮助。我有一个词典列表。应将每个字典写入单独的.csv文件中。我该怎么做呢?
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:
A,a
B,b
File2:
C,c
D,d
File3: ...
2 个解决方案
#1
2
You have several issues with your code that you need to resolve first.
您的代码有几个问题需要先解决。
- Variable names cannot be integers
- Variables a, b, c, d, e, f, g, h are all undefined.
- The argument that you pass into
csv.writer()
must have havewrite()
functionality - in your case it should be a File object. Hence you should usecsv.writer(csvfile)
, notcsv.writer(eachfilename)
.
变量名不能是整数
变量a,b,c,d,e,f,g,h都是未定义的。
传递给csv.writer()的参数必须具有write()功能 - 在您的情况下,它应该是File对象。因此,您应该使用csv.writer(csvfile),而不是csv.writer(eachfilename)。
更多相关文章
- 如何使用python 3检查文件夹是否包含文件
- 如何使用未受标头影响的python导入csv文件,其中第一列为非数值
- python在windows中的文件路径问题
- 套接字。接受错误24:对许多打开的文件
- python如何将一个txt文件里的转化为相应字典
- Python之错误异常和文件处理
- python解析json文件读取Android permission说明
- python 之 logger日志 字典配置文件
- [置顶] Python + C/C++ 嵌入式编程(1):多维数组Numpy.Array(