Asked By – Li-aung Yip
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')
Now we will see solution for issue: How do I write data into CSV format as string (not file)?