How to write UTF-8 in a CSV file

前端 未结 7 1487
一生所求
一生所求 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 04:06

    For me the UnicodeWriter class from Python 2 CSV module documentation didn't really work as it breaks the csv.writer.write_row() interface.

    For example:

    csv_writer = csv.writer(csv_file)
    row = ['The meaning', 42]
    csv_writer.writerow(row)
    

    works, while:

    csv_writer = UnicodeWriter(csv_file)
    row = ['The meaning', 42]
    csv_writer.writerow(row)
    

    will throw AttributeError: 'int' object has no attribute 'encode'.

    As UnicodeWriter obviously expects all column values to be strings, we can convert the values ourselves and just use the default CSV module:

    def to_utf8(lst):
        return [unicode(elem).encode('utf-8') for elem in lst]
    
    ...
    csv_writer.writerow(to_utf8(row))
    

    Or we can even monkey-patch csv_writer to add a write_utf8_row function - the exercise is left to the reader.

    0 讨论(0)
提交回复
热议问题