title: How do I write data into CSV format as string (not file)?
body: <p>I want to cast data like <code>[1,2,'a','He said "what do you mean?"']</code> to a CSV-formatted string. </p>
  
  <p>Normally one would use <code>csv.writer()</code> for this, because it handles all the crazy edge cases (comma escaping, quote mark escaping, CSV dialects, etc.) The catch is that <code>csv.writer()</code> expects to output to a file object, not to a string.</p>
  
  <p>My current solution is this somewhat hacky function:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Can anyone give a more elegant solution that still handles the edge cases well?</p>
  
  <p>Edit: Here's how I ended up doing it:</p>
  
  <pre><code>def csv2string(data):
      si = StringIO.StringIO()
      cw = csv.writer(si)
      cw.writerow(data)
      return si.getvalue().strip('\r\n')
  </code></pre>