How do I write data into CSV format as string (not file)?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC B Schuberts Piano Sonata No 16 D
--
Chapters
00:00 Question
01:14 Accepted answer (Score 73)
01:40 Answer 2 (Score 245)
02:12 Answer 3 (Score 8)
03:03 Answer 4 (Score 6)
03:24 Thank you
--
Full question
https://stackoverflow.com/questions/9157...
Accepted answer links:
[StringIO]: https://docs.python.org/2/library/string...
[cStringIO]: https://docs.python.org/2/library/string...
Answer 3 links:
[source and test]: https://gist.github.com/sloev/1625dd0020...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #csv
#avk47
--
Track title: CC B Schuberts Piano Sonata No 16 D
--
Chapters
00:00 Question
01:14 Accepted answer (Score 73)
01:40 Answer 2 (Score 245)
02:12 Answer 3 (Score 8)
03:03 Answer 4 (Score 6)
03:24 Thank you
--
Full question
https://stackoverflow.com/questions/9157...
Accepted answer links:
[StringIO]: https://docs.python.org/2/library/string...
[cStringIO]: https://docs.python.org/2/library/string...
Answer 3 links:
[source and test]: https://gist.github.com/sloev/1625dd0020...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #csv
#avk47
ANSWER 1
Score 264
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 changed a bit 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'
ACCEPTED ANSWER
Score 73
You could use StringIO instead of your own Dummy_Writer:
This module implements a file-like class,
StringIO, that reads and writes a string buffer (also known as memory files).
There is also cStringIO, which is a faster version of the StringIO class.
ANSWER 3
Score 7
I found the answers, all in all, a bit confusing. For Python 2, this usage worked for me:
import csv, io
def csv2string(data):
si = io.BytesIO()
cw = csv.writer(si)
cw.writerow(data)
return si.getvalue().strip('\r\n')
data=[1,2,'a','He said "what do you mean?"']
print csv2string(data)
ANSWER 4
Score 0
Here's the version that works for utf-8. csvline2string for just one line, without linebreaks at the end, csv2string for many lines, with linebreaks:
import csv, io
def csvline2string(one_line_of_data):
si = BytesIO.StringIO()
cw = csv.writer(si)
cw.writerow(one_line_of_data)
return si.getvalue().strip('\r\n')
def csv2string(data):
si = BytesIO.StringIO()
cw = csv.writer(si)
for one_line_of_data in data:
cw.writerow(one_line_of_data)
return si.getvalue()