When opening files in python, I get the error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
My code is
p=open("afile.txt","r")
file=p.read()
When opening files in python, I get the error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
My code is
p=open("afile.txt","r")
file=p.read()
This is a UnicodeError. You are trying to read a Unicode character in with the ASCII codec.
Try:
import codecs
p = codecs.open("afile.txt", "r", "utf-8")
f = p.read()
or
import codecs
p = codecs.open("afile.txt", "r", "utf-16")
f = p.read()
You should also probably consider using:
with codecs.open("afile.txt", "r", "utf-8") as f:
# Do whatever you want with f
This makes it able to auto-close the file when you exit the with
statement.
You could also try iso-8859-15
or cp437
Take a look at https://pypi.python.org/pypi/chardet and https://docs.python.org/3/library/codecs.html#codecs.open.