简体   繁体   中英

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

I am just starting up 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.

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. In all the fairness, this is not python best use case.

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:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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