首页 > 解决方案 > 为什么读取包含中文字符的文件时会出现 UnicodeDecodeError?

问题描述

>>> 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中运行正常。

标签: pythonencoding

解决方案


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

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

您的语言环境可能应该首选编码指定为 UTF-8,但我认为这取决于操作系统和语言设置。


推荐阅读