开发者

Convert array to CSV/TSV-formated string in Python

开发者 https://www.devze.com 2022-12-29 07:57 出处:网络
Python provides csv.DictWriter for outputting CSV to a file. What is the simplest开发者_开发知识库 way to output CSV to a string or to stdout?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号