Convert array to CSV/TSV-formated string in Python.

Posted by dreeves on Stack Overflow See other posts from Stack Overflow or by dreeves
Published on 2010-05-04T20:38:06Z Indexed on 2010/05/04 20:48 UTC
Read the original article Hit count: 372

Filed under:
|
|
|
|

Python provides csv.DictWriter for outputting CSV to a file. What is the simplest way to output CSV to a string or to stdout?

For example, given a 2D array like this:

[["a b c", "1,2,3"],
 ["i \"comma-heart\" you", "i \",heart\" u, too"]]

return the following string:

"a b c, \"1, 2, 3\"\n\"i \"\"comma-heart\"\" you\", \"i \"\",heart\"\" u, too\""

which when printed would look like this:

a b c, "1,2,3"
"i ""heart"" you", "i "",heart"" u, too"

(I'm taking csv.DictWriter's word for it that that is in fact the canonical way to output that array as CSV. Excel does parse it correctly that way, though Mathematica does not. From a quick look at the wikipedia page on CSV it seems Mathematica is wrong.)

One way would be to write to a temp file with csv.DictWriter and read it back with csv.DictReader. What's a better way?

TSV instead of CSV

It also occurs to me that I'm not wedded to CSV. TSV would make a lot of the headaches with delimiters and quotes go away: just replace tabs with spaces in the entries of the 2D array and then just intersperse tabs and newlines and you're done. Let's include solutions for both TSV and CSV in the answers to make this as useful as possible for future searchers.

© Stack Overflow or respective owner

Related posts about csv

Related posts about python