简体   繁体   English

将Python的列表或字典写入CSV文件(行包含多个列)

[英]Writing Python's List or Dictionary into CSV file (Row containing More than One Column)

I am just starting up Python!! 我刚刚启动Python!

i want to make a CSV file where i have a dictionary and i want to print each member of it in its own column in the same row. 我想制作一个有字典的CSV文件,我想将它的每个成员打印在同一行的自己的列中。

like i have an array of dictionaries and i want each row to represent one of them and each column of each row to represent an item inside. 就像我有一个字典数组,我希望每一行代表其中之一,每行每一列代表其中的一项。

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

the thing i output now is a row which contains the data in the first dictionary, i just want them seperated, each in its own column within its row. 我现在输出的是一行,其中包含第一个字典中的数据,我只想将它们分开,每个都在其行内的自己的列中。

It is surprising there are so many questions here that try to fill in some data in while loop and input() command. 令人惊讶的是,这里有如此多的问题试图在while循环和input()命令中填充一些数据。 In all the fairness, this is not python best use case. 公平地说,这不是python的最佳用例。

Imagine you had the dictionary just filled in your code: 想象一下,您刚才在字典中填写了代码:

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

After that you can export to csv easily: 之后,您可以轻松导出到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)

Note there are many questiona about csv module on SO as well as there are examples in documentation . 请注意,关于SO上的csv模块有很多问题,并且在文档中还有示例

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

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