Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 318: ordinal not in range(128)

I am trying to open and readlines a .txt file that contains a large amount of text. Below is my code, i dont know how to solve this problem. Any help would be very appreciated.

file = input("Please enter a .txt file: ")
myfile = open(file)
x = myfile.readlines()
print (x)

when i enter the .txt file this is the full error message is displayed below:

line 10, in <module> x = myfile.readlines()
line 26, in decode return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 318: ordinal not in range(128)
like image 222
dtidy Avatar asked Feb 05 '23 09:02

dtidy


2 Answers

Instead of using codecs, I solve it this way:

def test():
    path = './test.log'
    file = open(path, 'r+', encoding='utf-8')
    while True:
        lines = file.readlines()
        if not lines:
            break
        for line in lines:
            print(line)

You must give encoding param precisely.

like image 64
yanzi1225627 Avatar answered Feb 08 '23 14:02

yanzi1225627


You can also try to encode :

with open(file) as f:
    for line in f: 
         line = line.encode('ascii','ignore').decode('UTF-8','ignore')
         print(line)
like image 41
Nicole Douglas Avatar answered Feb 08 '23 14:02

Nicole Douglas