Search code examples
pythonstringhosts

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


I created simple code to remove digits from hosts file.

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)

The script runs fine, until, it returns an error. I've examined the hosts file where it broke and the data is not at fault.

The error returned is:

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

I understand its pointing to a library, is it to do with running memory?
Should I be running the script differently?
Im running this code from inside the python IDLE shell

Solution

  • Encoding issue related to the open() function