【问题标题】:Writing Python's List or Dictionary into CSV file (Row containing More than One Column)将 Python 的列表或字典写入 CSV 文件(包含多列的行)
【发布时间】:2017-09-22 15:44:01
【问题描述】:

我正在启动 Python!

我想制作一个 CSV 文件,其中我有一本字典,并且我想在同一行的自己的列中打印它的每个成员。

就像我有一个字典数组,我希望每一行代表其中一个,每一行的每一列代表里面的一个项目。

import csv


"... we are going to create an array of dictionaries and print them all..."

st_dic = []

true = 1

while true:
    dummy = input("Please Enter name, email, mobile, university, major")
    x = dummy.split(",")

    if "Stop" in x:
        break

    dict ={"Name":x[0],"Email":x[1],"Mobile":x[2],"University":x[3],"Major":x[4]}
    st_dic.append(dict)

f2 = open("data.csv" , "w")

with open("data.csv", "r+") as f:
    writer = csv.writer(f)
    for item in st_dic:
        writer.writerow([item["Name"], item["Email"], item["Mobile"] , item["University"] , item["Major"]])
    f.close()

我现在输出的是一行,其中包含第一个字典中的数据,我只想将它们分开,每个在其行内的自己的列中。

【问题讨论】:

    标签: python csv dictionary


    【解决方案1】:

    令人惊讶的是这里有这么多问题试图在while循环和input()命令中填写一些数据。平心而论,这不是 python 的最佳用例。

    想象一下,您的代码刚刚填写了字典:

    dict1 = {'name': "Kain", 'email': 'make_it_up@something.com'} 
    dict2 = {'name': "Abel", 'email': 'make_it_up2@otherthing.com'}
    dict_list = [dict1, dict2]
    

    之后,您可以轻松导出为 csv:

    import csv 
    with open('data.csv', 'w') as f: 
        w = csv.DictWriter(f, ['name', 'email'], lineterminator='\n')
        w.writeheader()
        for row in dict_list:  
            w.writerow(row)
    

    请注意,SO 上有很多关于csv 模块的问题 还有examples in documentation

    【讨论】:

      猜你喜欢
      • 2015-11-14
      • 2014-06-30
      • 2016-03-01
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多