How do I write data into CSV format as string (not file)?

后端 未结 6 1365
借酒劲吻你
借酒劲吻你 2020-11-28 04:56

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

6条回答
  •  忘掉有多难
    2020-11-28 05:51

    I found the answers, all in all, a bit confusing. For Python 2, this usage worked for me:

    import csv, io
    
    def csv2string(data):
        si = io.BytesIO()
        cw = csv.writer(si)
        cw.writerow(data)
        return si.getvalue().strip('\r\n')
    
    data=[1,2,'a','He said "what do you mean?"']
    print csv2string(data)
    

提交回复
热议问题