. , .
, , .
CSV , . - https://en.wikipedia.org/wiki/Comma-separated_values
, , .
Suppose that the input ['1,2,3', 'Hello'], output in the CSV should be "1,2,3", "Hello", for this you can use the codes below.
>>> ",".join('"{0}"'.format(s) for s in ['1,2,3', 'Hello'])
'"1,2,3","Hello"'
But you will encounter problems when there are special characters in the text, such as ", \netc.
The python csv library handled all edge cases for you.
Write to file
May use @Dominic Rodger's answer.
>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'wb'))
>>> spamWriter.writerow(['Spam', 'Lovely, Spam'])
Write to string
From fooobar.com/questions/15185 / ... .
In Python 3:
>>> import io
>>> import csv
>>> output = io.StringIO()
>>> csvdata = [1,2,'a','He said "what do you mean?"',"Whoa!\nNewlines!"]
>>> writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
>>> writer.writerow(csvdata)
59
>>> output.getvalue()
'1,2,"a","He said ""what do you mean?""","Whoa!\nNewlines!"\r\n'
Some details need to be slightly modified for Python 2:
>>> output = io.BytesIO()
>>> writer = csv.writer(output)
>>> writer.writerow(csvdata)
57L
>>> output.getvalue()
'1,2,a,"He said ""what do you mean?""","Whoa!\nNewlines!"\r\n'