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.

您的代码有几个问题需要先解决。

  1. Variable names cannot be integers
  2. 变量名不能是整数

  3. Variables a, b, c, d, e, f, g, h are all undefined.
  4. 变量a,b,c,d,e,f,g,h都是未定义的。

  5. 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).
  6. 传递给csv.writer()的参数必须具有write()功能 - 在您的情况下,它应该是File对象。因此,您应该使用csv.writer(csvfile),而不是csv.writer(eachfilename)。

更多相关文章

  1. 如何使用python 3检查文件夹是否包含文件
  2. 如何使用未受标头影响的python导入csv文件,其中第一列为非数值
  3. python在windows中的文件路径问题
  4. 套接字。接受错误24:对许多打开的文件
  5. python如何将一个txt文件里的转化为相应字典
  6. Python之错误异常和文件处理
  7. python解析json文件读取Android permission说明
  8. python 之 logger日志 字典配置文件
  9. [置顶] Python + C/C++ 嵌入式编程(1):多维数组Numpy.Array(

随机推荐

  1. 怎样使一个Android应用不被杀死//Android
  2. Android开发者e周报 第4期
  3. 全面解析Android事件分发机制:一篇足矣!
  4. Android(安卓), and
  5. Android支付密码输入框
  6. Android平板电脑全球已激活1200万台 今年
  7. Android面试看重你什么?(推荐!!!)
  8. Android4.0 Design之UI设计易犯的错误1
  9. Android进程的so注入--Poison(稳定注入版)
  10. 想抢先体验Android操作系统的魅力吗?那就