【问题标题】:encoding='utf-8' raise UnicodeEncodeError when opening utf-8 file with Chinese charencoding='utf-8' 在打开带有中文字符的 utf-8 文件时引发 UnicodeEncodeError
【发布时间】:2013-06-04 20:21:45
【问题描述】:

我无法打开任何中文字符的文件,编码设置为utf-8

text = open('file.txt', mode='r', encoding='utf-8').read()
print(text)

UnicodeEncodeError: 'charmap' codec can't encode character '\u70e6' in position 0: character maps to <undefined>

文件是 100% utf-8。
http://asdfasd.net/423/file.txt
http://asdfasd.net/423/test.py
如果我删除 encoding='utf-8' 一切正常。

这里的编码有什么问题?
我在打开文件时总是使用encoding='utf-8',我现在不知道现在发生了什么。

【问题讨论】:

  • 您在读取文件时没有问题,但在写入(或打印)时遇到了问题。阅读会导致UnicodeDecodeError,但您有一个编码问题。

标签: python encoding utf-8 python-3.x


【解决方案1】:

您看到的异常来自打印您的数据。打印要求您将数据编码为终端或 Windows 控制台使用的编码。

您可以从异常中看到这一点(以及从回溯中,但您没有包含它);如果您在解码数据时遇到问题(当您从文件中读取时会发生这种情况),那么您会得到 UnicodeDecodeError,而您会得到 UnicodeEncodeError

您需要调整终端或控制台编码,或者不打印数据

请参阅http://wiki.python.org/moin/PrintFails 获取故障排除帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    相关资源
    最近更新 更多