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')
StringIO()
is in theio
library. – Aristidereturn si.getvalue().strip()
--unless for some reason you need to preserve spaces at the end. – MTKnife