【问题标题】:Why did I get UnicodeDecodeError when I read a file which contains Chinese characters?为什么读取包含中文字符的文件时会出现 UnicodeDecodeError?
【发布时间】:2020-05-27 15:18:40
【问题描述】:
>>> path = 'name.txt'
>>> content = None
>>> with open(path, 'r') as file:
...     content = file.readlines()
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/mnt/lustre/share/miniconda3/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 163: ordinal not in range(128)

当我运行这段代码来读取一个包含中文字符的文件时,我得到了一个错误。该文件使用 UTF-8 保存。我的python版本是3.6.5。但它在python2.7中运行正常。

【问题讨论】:

  • open 可以在 python3 中采用可选的“encoding”关键字...在 python 2 中,它会隐式尝试为您解码...大多数时候它是正确的...跨度>
  • with open(path, 'rb') 不是 r
  • 您是否阅读了错误信息? 'ascii' codec ... 你需要告诉它使用 UTF-8。
  • @Joran Python 2 的 open() 不解码。它只返回字节字符串。你可能会想到codecs.open()io.open()

标签: python encoding


【解决方案1】:

open 正在使用 ASCII 编解码器尝试读取文件。解决此问题的最简单方法是指定编码:

with open(path, 'r', encoding='utf-8') as file:

您的locale should probably specify preferred encoding 为UTF-8,但我认为这取决于操作系统和语言设置。

【讨论】:

  • 我可以通过使用它来读取文件而不会出错。但是当我尝试print (content[0]) 时,会出现同样的错误。
【解决方案2】:

Python 2.7 默认将文件读入字节串。

Python 3.x 默认将文件读入 Unicode 字符串,因此文件中的字节必须经过解码。

使用的默认编码因操作系统而异,但可以通过调用locale.getpreferredencoding(False) 来确定。在 Linux 系统上这通常是 utf8,但 Windows 系统会返回本地化的 ANSI 编码,例如cp1252 适用于美国/西欧 Windows 版本。

在 Python 3 中,指定您期望的文件编码,以免依赖于特定于语言环境的默认值。例如:

with open(path,'r',encoding='utf8') as f:
    ...

您也可以在 Python 2 中执行此操作,但使用 io.open(),它与 Python 3 的 open() 兼容,并且将读取 Unicode 字符串而不是字节字符串。 io.open() 在 Python 3 中也可用,以实现可移植性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-07
    • 2018-12-26
    • 2019-08-08
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2013-08-12
    相关资源
    最近更新 更多