且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-21 17:21:48

找到一种解决方法:



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

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



/ p>

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!

found a way to solve this:

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

it worked.