简体   繁体   English

python将德语umlaute写入文件

[英]python write german umlaute into a file

I know, this question has been asked million times. 我知道,这个问题已被问过百万次。 But I am still stuck with it. 但我仍然坚持下去。 I am using python 2 and cannot change to python 3. 我使用的是python 2,无法更改为python 3。

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 file has: 然后文件有:

{'key': u'\xfcmlaut'}

I need {'key': 'ümlaut'} or {'key': u'ümlaut'} 我需要{'key': 'ümlaut'}{'key': u'ümlaut'}

What am I missing, I am still noob in encoding decoding things :/ 我缺少什么,我仍然编码解码的东西:/

I'm not sure why you want this format particularly, since it won't be valid to read into any other application, but never mind. 我不确定你为什么要特别想要这种格式,因为读入任何其他应用程序无效,但没关系。

The problem is that to write a dictionary to a file, it needs to be converted to a string - and to do that, Python calls repr on all its elements. 问题是要将字典写入文件,需要将其转换为字符串 - 为此,Python会调用其所有元素的repr

If you create the 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)

The easiest solution is to switch to python3, but since you can't do that, how about converting dictionary to json first before trying to save it into the file. 最简单的解决方案是切换到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')))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM