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')
解决方案
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.