Python writes German umlaute to file

I know this question has been asked millions of times. But I still stick to that. I am using python 2 and cannot upgrade to python 3.

The problem is this:

>>> w = u"ümlaut"
>>> w
>>> u'\xfcmlaut'
>>> print w
ümlaut
>>> dic = {'key': w}
>>> dic
{'key': u'\xfcmlaut'}
>>> f = io.open('testtt.sql', mode='a', encoding='UTF8')
>>> f.write(u'%s' % dic)

then the file has:

{'key': u'\xfcmlaut'}

I need {'key': 'ümlaut'}or{'key': u'ümlaut'}

What I miss, I'm still a noob in encoding decoding things: /

+4
source share
2 answers

I'm not sure why you want this format, especially since it will not be valid for reading in any other application, but it doesn’t matter.

The problem is that to write a dictionary into a file, you need to convert it to a string - and for this, Python calls reprfor all its elements.

If you create output manually as a string, all is well:

d = "{'key': '%s'}" % w
with io.open('testtt.sql', mode='a', encoding='UTF8') as f:
    f.write(d)
+2
source

- python3, , , json, .

import io
import json
import sys

reload(sys)
sys.setdefaultencoding('utf8')

w = u"ümlaut"
dic = {'key': w}
f = io.open('testtt.sql', mode='a', encoding='utf8')
f.write(unicode(json.dumps(dic, ensure_ascii=False).encode('utf8')))
+1

Source: https://habr.com/ru/post/1676809/


All Articles