For me, the UnicodeWriter class from the 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)
It works, but:
csv_writer = UnicodeWriter(csv_file) row = ['The meaning', 42] csv_writer.writerow(row)
will throw AttributeError: 'int' object has no attribute 'encode' .
Since UnicodeWriter explicitly expects all column values โโto be strings, we can convert the values โโourselves and simply 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 add the write_utf8_row function - the exercise remains for the reader.
Bojan Bogdanovic Sep 27 '17 at 15:11 2017-09-27 15:11
source share