I'm working on a Python tool that must be able to open files of UTF-8 and UTF-16 encoding. In Python 3.2, I use the following code to try opening the file using UTF-8, then try it with UTF-16 if there's a unicode error:
def readGridFromPath(self, filepath):
try:
self.readGridFromFile(open(filepath,'r',encoding='utf-8'))
except UnicodeDecodeError:
self.readGridFromFile(open(filepath,'r',encoding='utf-16'))
(readGridFromFile
will either run through to completion, or raise a UnicodeDecodeError
. )
However, when I run this code in Python 2.x, I get:
TypeError: 'encoding' is an invalid keyword argument for this function
I see in the docs that Python 2.x's open()
doesn't have an encoding
keyword. Is there any way around this that will allow me to make my code Python 2.x compatible?