简体   繁体   中英

Making every element of a list part of a CSV header

I have a list:

[cat, dog, mouse]

and I wish for all the list items to be headers in a csv file like this:

cat,dog,mouse
data,data,data
date,data,data

I have the following code to open a file, but I am not sure how to assign the animals to the headers:

with open(fname, 'w') as my_csv:
        my_csv.write(#cat,dog,mouse needs to go in here)
        csv_writer = csv.writer(my_csv, delimiter=',')

I don't want to explicitly write cat,dog,mouse as these animals can change due to user input choosing the animals further up the code.

I think the best way to do this would be to use csv.DictWriter . Here's an example with your problem:

import csv

with open('names.csv', 'w') as csvfile:
    fieldnames = ['Cat', 'Dog', 'Mouse']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'Cat': 'Data', 'Dog': 'Data', 'Mouse': 'Data'})

Just join the elements by , and then write it on the csv file.

li = ['cat', 'dog', 'mouse']
with open(fname, 'w') as my_csv:
    my_csv.write(','.join(li))
    csv_writer = csv.writer(my_csv, delimiter=',')

Just write the list as the first row. Also note that the file should be opened with newline='' in Python 3 or 'wb' in Python 2 for correct handling of newlines on all OSs:

li = ['cat', 'dog', 'mouse']
with open(fname, 'w', newline='') as my_csv:
    csv_writer = csv.writer(my_csv, delimiter=',')
    csv_writer.writerow(li)

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