I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this
[u'value 1', u'value 2', ...]
If I iterate through the values in the list i.e. for v in mylist: print v
they appear to be plain text.
And I can put a ,
between each with print ','.join(mylist)
And I can output to a file, i.e.
myfile = open(...)
print >>myfile, ','.join(mylist)
But I want to output to a CSV and have delimiters around the values in the list e.g.
"value 1", "value 2", ...
I can't find an easy way to include the delimiters in the formatting, e.g. I have tried through the join
statement. How can I do this?
import csv
with open(..., 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
Edit: this only works with python 2.x.
To make it work with python 3.x replace wb
with w
(see this SO answer)
with open(..., 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)