Reading files in Python 3.5 which have been generated in Python 2.7

41 Views Asked by At

I have run some scritp in Python 2.7 which generated a file, and when I tried to open it I found the following error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc0 in position 2623: ordinal not in range(128)

Any clue on how to open it in Python 3.5?

2

There are 2 best solutions below

1
rdas On

Your file is in utf-8 (probably). The ASCII codec can't decode unicode text.

You should use the proper codec. The file.read() function returns a bytes-like object. You can turn that into a string like so:

contents = str(file.read(), 'utf-8')
0
Jacques Gaudin On

You can specify the encoding when opening the file:

 with open(myfile, encoding='utf-8) as f:
     pass