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)
martineau
  • 119,623
  • 25
  • 170
  • 301
hhh
  • 50,788
  • 62
  • 179
  • 282
  • 2
    Does it help to open the file with `encoding='utf-8'`? – languitar Feb 06 '17 at 11:47
  • try to add: `#!/usr/bin/env python # -*- coding: utf-8 -*-` see this [answer](http://stackoverflow.com/questions/6289474/working-with-utf-8-encoding-in-python-source) – terence hill Feb 06 '17 at 11:55
  • @languitar no, it did not. – hhh Feb 06 '17 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! – hhh Feb 06 '17 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. – terence hill Feb 06 '17 at 12:21

2 Answers2

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.

Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
  • You can set encoding in `open` too – ᴀʀᴍᴀɴ Feb 06 '17 at 11:53
  • 1
    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`). – ShadowRanger Feb 06 '17 at 11:54
  • 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. – terence hill Feb 06 '17 at 12:01
-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

Community
  • 1
  • 1
terence hill
  • 3,354
  • 18
  • 31