ahhh
ahhh

Reputation: 123

Print elements of a list to a .csv file

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?

Upvotes: 4

Views: 14437

Answers (4)

ezdazuzena
ezdazuzena

Reputation: 6770

Though it looks like your question was more towards writing to a csv file rather than printing it to standard output, here an example to do the latter using StringIO:

import StringIO
import csv

a_list_from_csv_file = [['for', 'bar'], [1, 2]]
out_fd = StringIO.StringIO()
writer = csv.writer(out_fd, delimiter='|')
for row in a_list_from_csv_file:
    writer.writerow(row)
print out_fd.getvalue()

Like this you can use the different delimiters or escape characters as used by the csv you are reading.

Upvotes: 0

integer
integer

Reputation: 1075

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.

Upvotes: -1

dwich
dwich

Reputation: 1725

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

http://docs.python.org/library/csv.html#csv.writer

Upvotes: 7

Joril
Joril

Reputation: 20547

Assuming that "row" contains a list of strings, you could try using

print ",".join(row)

Upvotes: 4

Related Questions