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

dtidy picture dtidy · Jan 6, 2017 · Viewed 9.7k times · Source

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)

Answer

yanzi1225627 picture yanzi1225627 · Apr 26, 2017

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.