Python 无法写入包含utf8字符的文本文件

Python 无法写入包含utf8字符的文本文件,python,json,python-2.7,file,text,Python,Json,Python 2.7,File,Text,我正在尝试保存一个文本文件,其中包含像ááã等字符。但是,我目前失败了,无法使它与我在互联网上看到的内容一起工作 我目前的代码是: # -*- coding: utf-8 -*- import codecs import json test_dict = {'name': [u'Joe', u'Doe'], 'id': u'1:2:3', 'description': u'he w\xe1','fav': [1, 2]} final_text = line = "- " + json.dum

我正在尝试保存一个文本文件,其中包含像ááã等字符。但是,我目前失败了,无法使它与我在互联网上看到的内容一起工作

我目前的代码是:

# -*- coding: utf-8 -*-

import codecs
import json

test_dict = {'name': [u'Joe', u'Doe'], 'id': u'1:2:3', 'description': u'he w\xe1','fav': [1, 2]}
final_text = line = "- " + json.dumps(test_dict) + "\n"

filename = 'C:\Users\PLUX\Desktop\data.txt'
f = codecs.open(filename,'w','utf8')
f.write(line)
哪些产出:

- {"description": "he w\u00e1", "fav": [1, 2], "name": ["Joe", "Doe"], "id": "1:2:3"}
我希望它能够输出:

- {"description": "he wá", "fav": [1, 2], "name": ["Joe", "Doe"], "id": "1:2:3"}
有人能帮我吗?

\u00e1是字符的unicode转义版本。加载数据时,json模块会将其转换回预期的表示形式

如果您确实希望在文件中使用未加盖的版本,请将sure_ascii=False传递给json.dumps:

要写入文件,请执行以下操作:

>>> final_text = u'- ' + json.dumps(test_dict, ensure_ascii=False) + u'\n'
>>> with io.open('foo.txt', 'w', encoding='utf-8') as f:
...     f.write(final_text)

注意,我已经将要连接的字符串显式标记为unicode,因为我不希望Python 2将结果有效地转换为bytestring。

如果您可以使用Python 3,那么很遗憾,不需要。我只能使用Python 2.7。非常感谢你的评论
>>> final_text = u'- ' + json.dumps(test_dict, ensure_ascii=False) + u'\n'
>>> with io.open('foo.txt', 'w', encoding='utf-8') as f:
...     f.write(final_text)