0

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.

1
  • Why don't you just join the elements with a comma and write this as the first line: ','.join(list) by the way using variable name list is poor form you should use something else like header_names or something Commented Apr 17, 2015 at 13:17

3 Answers 3

1

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'}) 
Sign up to request clarification or add additional context in comments.

Comments

0

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=',') 

Comments

0

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) 

Comments