Tim Gruenhagen
Tim Gruenhagen

Reputation: 29

How to export a single list into a csv file?

I have written simple code to make a list of strings, all I want is to export that list on its own to a csv file that I can open with excel. I have read through multiple answers and still can't get it to work. Running python 3. I believe my problem is with either creating the new csv file or having it find and write to a preexisting one, any ideas on this?

Upvotes: 2

Views: 4088

Answers (2)

McGlothlin
McGlothlin

Reputation: 2099

Check out the csv module. It would look something like this:

import csv
mylist = ['foo', 'bar', 'baz']
with open('myfile.csv', 'w', newline='\n') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(['Header1', 'Header2', 'Header3'])
    csvwriter.writerow(mylist)

Output:

Header1,Header2,Header3
foo,bar,baz

This code will create a file if it doesn't exist, or overwrite an existing file called myfile.csv. More info here.

Upvotes: 3

be_good_do_good
be_good_do_good

Reputation: 4441

yourlist = ['string1', 'string2']
data = ','.join(yourlist)
fh = open('myfile.csv', 'w+')
fh.write(data)
fh.close()

If you multiple lists(say list of lists) to be written to CSV, then loop them over using for. Above example is to do using without any imports.

You can also do alternatively using csv module (import csv)

Upvotes: 2

Related Questions