I want to cast data like [1,2,'a','He said "what do you mean?"']
to a CSV-formatted string.
Normally one would use csv.writer()
for this, because it handles all the crazy edge cases (comma escaping, quote mark escaping, CSV dialects, etc.) The catch is that csv.writer()
expects to output to a file object, not to a string.
My current solution is this somewhat hacky function:
def CSV_String_Writeline(data):
class Dummy_Writer:
def write(self,instring):
self.outstring = instring.strip("\r\n")
dw = Dummy_Writer()
csv_w = csv.writer( dw )
csv_w.writerow(data)
return dw.outstring
Can anyone give a more elegant solution that still handles the edge cases well?
Edit: Here's how I ended up doing it:
def csv2string(data):
si = StringIO.StringIO()
cw = csv.writer(si)
cw.writerow(data)
return si.getvalue().strip('\r\n')
Since your example only has one row of data, you could simply use
Obviously, if the input data has a more complex form such as a dictionary or 2d array, this simple answer would become more complex.
In Python 3:
Some details need to be changed a bit for Python 2:
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:
I found the answers, all in all, a bit confusing. For Python 2, this usage worked for me:
You could use
StringIO
instead of your ownDummy_Writer
:There is also
cStringIO
, which is a faster version of theStringIO
class.