Python 3.11 - 删除数字代码运行并有效但导致错误

Python 3.11 - Remove digit code runs and works but results in error

我创建了简单的代码来从主机文件中删除数字。

with open(r'C:\Windows\System32\drivers\etc\hosts', 'r') as infile, open(r'C:\XXXX\XXX\X.txt', 'w') as outfile:
    for i in infile:
        if not i[0].isdigit():
            print("Line Skipped")
        else:
            if int(i[0]) == 0:
                B = i[8:]
                outfile.write(B)
            elif int(i[0]) == 1:
                B = i[10:]
                outfile.write(B)

脚本运行良好,直到 returns 出错。 我检查了损坏的主机文件,数据没有错误。

返回的错误是:

Traceback (most recent call last):<br>
  File "<pyshell#142>", line 2, in <module><br>
    for i in infile:<br>
  File "C:\XXX\Python\Python311\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]<br>
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 4244: character maps to undefined

我知道它指向一个库,它与 运行 内存有关吗?
我应该 运行 脚本不同吗?
Im 运行 此代码来自 python IDLE shell

与 open() 函数相关的编码问题