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.
We use StringIO for this
myFakeFile = StringIO.StringIO()
wtr = csv.DictWriter( myFakeFile, headings )
...
myFakeFile.getvalue()
Usually works.
精彩评论