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
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.