【问题标题】:Failing to write text file with utf8 characters无法使用 utf8 字符写入文本文件
【发布时间】:2019-08-11 12:06:55
【问题描述】:

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

我当前的代码是:

# -*- 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"}

谁能帮帮我?

【问题讨论】:

  • 如果你可以使用 Python 3
  • 不幸的是没有。我只能使用 Python 2.7。非常感谢您的评论

标签: python json python-2.7 file text


【解决方案1】:

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

如果您确实想要文件中未封装的版本,请将ensure_ascii=False 传递给json.dumps

>>> print json.dumps(test_dict, ensure_ascii=False)
{"description": "he wá", "fav": [1, 2], "name": ["Joe", "Doe"], "id": "1:2:3"}

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

>>> 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 “有用地”将结果转换为字节字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多