该错误通常是由于文件编码问题引起的。需要确保在打开文件时使用正确的编码格式。例如,如果使用的是 utf-8 编码,应该这样打开文件:
with open('file.txt', encoding='utf-8') as f:
# some code here
另外,也可能是因为文件路径和名称中包含非 ASCII 字符,可以使用 Python 中的 pathlib 模块解决该问题:
from pathlib import Path
path = Path('/path/to/file.txt')
with path.open(encoding='utf-8') as f:
# some code here