[英]Writing Python's List or Dictionary into CSV file (Row containing More than One Column)
我剛剛啟動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()
我現在輸出的是一行,其中包含第一個字典中的數據,我只想將它們分開,每個都在其行內的自己的列中。
令人驚訝的是,這里有如此多的問題試圖在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.