How to write UTF-8 in a CSV file

前端 未结 7 1521
一生所求
一生所求 2020-11-27 03:30

I am trying to create a text file in csv format out of a PyQt4 QTableWidget. I want to write the text with a UTF-8 encoding because it contains special characte

7条回答
  •  渐次进展
    2020-11-27 03:44

    A very simple hack is to use the json import instead of csv. For example instead of csv.writer just do the following:

        fd = codecs.open(tempfilename, 'wb', 'utf-8')  
        for c in whatever :
            fd.write( json.dumps(c) [1:-1] )   # json dumps writes ["a",..]
            fd.write('\n')
        fd.close()
    

    Basically, given the list of fields in correct order, the json formatted string is identical to a csv line except for [ and ] at the start and end respectively. And json seems to be robust to utf-8 in python 2.*

提交回复
热议问题