Writing CSV file with umlauts causing “UnicodeEnco

2020-03-30 08:29发布

问题:

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)

回答1:

Add a parameter encoding to the open() and set it to 'utf8'.

import csv

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

Edit: Removed the use of io library as open is same as io.open in Python 3.



回答2:

This solution should work on both python2 and 3 (not needed in python3):

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
data="ääÖ"
with open("test.csv", "w") as fp:
    a = csv.writer(fp, delimiter=";")
    a.writerows(data)

Credits to: Working with utf-8 encoding in Python source