2

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)
5
  • 2
    Does it help to open the file with encoding='utf-8'? Commented Feb 6, 2017 at 11:47
  • try to add: #!/usr/bin/env python # -*- coding: utf-8 -*- see this answer Commented Feb 6, 2017 at 11:55
  • @languitar no, it did not. Commented Feb 6, 2017 at 12:02
  • @terencehill that is not the issue here, encoding parameter needed to be added in the open function as instructed by yper. Thank you for your answers! Commented Feb 6, 2017 at 12:10
  • Actually this doesn't work with python2X and do you realised that the solution given by yper is exactly the same as suggested by @languitar above? Anyway with python3 the solution accepted it's correct. Commented Feb 6, 2017 at 12:21

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You can set encoding in open too
In Python 3, open and io.open are the exact same thing. It's only in Python 2 where they differ (where io.open behaves like Python 3 open).
This solution works with python3 on my OSX but gives the error with python2.7. The error is in the line when data is set so before the call to open and the specification of the encoding.
-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.