tags:

views:

456

answers:

4

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

any suggestions welcome :)

+3  A: 

Use the csv module.

Ignacio Vazquez-Abrams
A: 

You could use the string.join method in this case.

Split over a few of lines for clarity - here's an interactive session

>>> a = ['a','b','c']
>>> first = '", "'.join(a)
>>> second = '"%s"' % first
>>> print second
"a", "b", "c"

Or as a single line

>>> print ('"%s"') % '", "'.join(a)
"a", "b", "c"

However, you may have a problem is your strings have got embedded quotes. If this is the case you'll need to decide how to escape them.

The CSV module can take care of all of this for you, allowing you to choose between various quoting options (all fields, only fields with quotes and seperators, only non numeric fields, etc) and how to esacpe control charecters (double quotes, or escaped strings). If your values are simple, string.join will probably be OK but if you're having to manage lots of edge cases, use the module available.

Robert Christie
+5  A: 
import csv

myfile = open(..., 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
Alex Martelli
Do note that the `csv` module in 2.x does not deal properly with unicodes; see the module documentation for examples on how to deal with this. http://docs.python.org/library/csv.html
Ignacio Vazquez-Abrams
A: 

Use python's csv module for reading and writing comma or tab-delimited files. The csv module is preferred because it gives you good control over quoting.

For example, here is the worked example for you:

import csv
data = ["value %d" % i for i in range(1,4)]

out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(data)

Produces:

"value 1","value 2","value 3"
vy32