how to interpret this error “UnicodeDecodeError: &

2020-04-10 04:32发布

I'm trying to run the below code in 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)

Then I got the error 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)
The source is all in English, so not sure what is going on with here? Thank you very much in advance!

1条回答
劳资没心,怎么记你
2楼-- · 2020-04-10 04:54

found a way to solve this:

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

it worked.

查看更多
登录 后发表回答