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

后端 未结 6 1367
借酒劲吻你
借酒劲吻你 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:29

    Here's the version that works for utf-8. csvline2string for just one line, without linebreaks at the end, csv2string for many lines, with linebreaks:

    import csv, io
    
    def csvline2string(one_line_of_data):
        si = BytesIO.StringIO()
        cw = csv.writer(si)
        cw.writerow(one_line_of_data)
        return si.getvalue().strip('\r\n')
    
    def csv2string(data):
        si = BytesIO.StringIO()
        cw = csv.writer(si)
        for one_line_of_data in data:
            cw.writerow(one_line_of_data)
        return si.getvalue()
    

提交回复
热议问题