读取文本文件时如何修复这个 cp950“非法多字节序列”UnicodeDecodeError?

vic*_*192 4 python python-3.x

我的老师教我们如何使用“exec”,但我得到了一个错误:

UnicodeDecodeError: 'cp950' codec can't decode byte 0xe6 in position 1814: illegal multibyte sequence
Run Code Online (Sandbox Code Playgroud)

我用:

exec(open("somefile.py").read())
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?

Sha*_*ger 5

鉴于这可能是 Python 3 源代码,可能的编码是 UTF-8(这是 Python 3 源代码的标准编码)。

如果是这种情况,更改open("somefile.py")open("somefile.py", encoding="utf-8")将显式指定编码,覆盖区域设置默认值,这应该允许您正确读取它。

对于惯用代码,您还需要使用with语句(以保证文件的确定性关闭),使其:

with open("somefile.py", encoding="utf-8") as f:
    exec(f.read())
Run Code Online (Sandbox Code Playgroud)