I am reading in a csv file and dealing with each line as a list. At the end, I'd like to reprint to a .csv file, but the lines aren't necessarily even. I obviously cannot just go "print row"
, since this will print it as a list. How can I print it in .csv format?
views:
53answers:
3
+1
A:
Assuming that "row" contains a list of strings, you could try using
print ",".join(row)
Joril
2010-07-12 13:04:38
+4
A:
Read manual, there's a CSV writer method (with example too). Don't print the data, store them and then write them into CSV file
dwich
2010-07-12 13:04:53
The CSV module is definitely your friend here. It was this module that made me understand what the “batteries included” bit of Python’s philosophy meant.
Paul D. Waite
2010-07-12 14:10:09
A:
What do you mean by "the lines aren't necessarily even"? Are you using a homebrew CSV parser or are you using the csv module?
If the former and there's nothing special you need to escape, you could try something like
print ",".join([ '"' + x.replace('"', '""') + '"' for x in row])
If you don't want ""s around each field, maybe make a function like escape_field()
that checks if it needs to be wrapped in double quotes and/or escaped.
integer
2010-07-12 13:10:20