如何解释此错误"UnicodeDecodeError:'ascii'编解码器无法解码164位的字节0xe2:序号不在范围内(128)"

Pen*_*nny 3 python encoding

我正在尝试在python 3中运行以下代码:

def func(file):
    for file in os.listdir(cwd):
        if file.endswith('.html'):
                f = open(file, "r+")
                text  = re.sub(r'cat',' ', f.read())
                f.close()
                f = open(file, "w")
                f.write(text)
                f.close()

file = os.listdir(cwd)
func(file)
Run Code Online (Sandbox Code Playgroud)

然后我收到错误File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 164: ordinal not in range(128)
来源全是英文,所以不知道这里发生了什么?非常感谢你提前!

Pen*_*nny 6

找到了解决这个问题的方法:

f = open(file, encoding = 'utf-8', mode = "r+")
f = open(file, encoding = 'utf-8', mode = "w")

有效.