【发布时间】: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()。