Need help converting text to csv format

Tim Golden mail at timgolden.me.uk
Fri Nov 21 11:22:16 EST 2008


Tim Chase wrote:
>>  >>> qfields = ['"' + fld.strip() + '"' for fld in (num,desc,date)]
>>  >>> out = qfields.join(',')
> 
> Just a quick note here to prevent the confusion of the OP...this should be
> 
>   ','.join(qfields)

To be honest, it's so easy to use the stdlib csv module
that I'd always recommend that, especially as it covers
all those annoying corner cases with embedded commas and
quotes and stuff. And it's tested to hell and back.


In general, for a list of field tuples:

<code>
import csv

fields = [
  ("Tim Golden", 40, "inf,o1"),
  ("Fred Smith", 25, "info2"),
  ("Joe O'Reilly", 55, 'inf,"blah",o3'), ## lots of messiness
]

ofile = open ("data.csv", "wb")
try:
  writer = csv.writer (ofile)
  writer.writerows ([[str (i) for i in f] for f in fields])
finally:
  ofile.close ()

</code>



More information about the Python-list mailing list