python - 为什么读取包含中文字符的文件时会出现 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中运行正常。
解决方案
推荐阅读
- node.js - 如何将 Moodle 中的学生数据导入 LTI 工具(Web 应用程序)
- html - 如何在其 flexbox 父容器包装之前使子 div 包装?
- pytorch - PyTorch Jupyter Notebook 图像无法找到火炬
- firebase - 我的 FirebaseStorage 方法没有在 Flutter 中运行。在 `firebase_storage: ^4.0.0` 之后
- javascript - 具有嵌套父项和子项的复选框树视图。?
- react-native - React navigation v5 - 如何从底部标签打开抽屉并显示底部标签的抽屉背面
- selenium - 无法在 xpath 中使用和条件定位元素
- reactjs - React 测试库:渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null
- python - 使用 Selenium 和 Beautifulsoup 进行 Python 抓取,仅提取超链接 href 无链接
- c++ - C++中队列的实现