0

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()
DavidG
  • 24,279
  • 14
  • 89
  • 82
Max Coates
  • 78
  • 1
  • 5
  • 6
    Possible duplicate of [UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)](http://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20) – Karthikeyan KR Mar 17 '17 at 13:10

1 Answers1

0

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.

cmeadows
  • 185
  • 2
  • 12