hhh hhh - 4 years ago 140
Python Question

Writing CSV file with umlauts causing "UnicodeEncodeError: 'ascii' codec can't encode character"

I am trying to write characters with double dots (umlauts) such as ä, ö and Ö. I am able to write it to the file with

data.encode("utf-8")
but the result
b'\xc3\xa4\xc3\xa4\xc3\x96'
is not nice (UTF-8 as literal characters). I want to get
"ääÖ"
as written stored to a file.

How can I write data with umlaut characters to a CSV file in Python 3?

import csv
data="ääÖ"
with open("test.csv", "w") as fp:
a = csv.writer(fp, delimiter=";")
data=resultFile
a.writerows(data)


Traceback:

File "<ipython-input-280-73b1f615929e>", line 5, in <module>
a.writerows(data)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe4' in position 15: ordinal not in range(128)

Answer Source

Instead of open, use io.open from the io library, where you can set the encoding.

import io
import csv

data = "ääÖ"
with io.open("test.csv", 'w', encoding='utf8') as fp:
    a = csv.writer(fp, delimiter=";")
    a.writerows(data)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download