Searching for equivalent of FileNotFoundError in Python 2
If FileNotFoundError
isn't there, define it:
try: FileNotFoundErrorexcept NameError: FileNotFoundError = IOError
Now you can catch FileNotFoundError
in Python 2 since it's really IOError
.
Be careful though, IOError
has other meanings. In particular, any message should probably say "file could not be read" rather than "file not found."
You can use the base class exception EnvironmentError and use the 'errno' attribute to figure out which exception was raised:
from __future__ import print_functionimport osimport errnotry: open('no file of this name') # generate 'file not found error'except EnvironmentError as e: # OSError or IOError... print(os.strerror(e.errno))
Or just use IOError in the same way:
try: open('/Users/test/Documents/test') # will be a permission errorexcept IOError as e: print(os.strerror(e.errno))
That works on Python 2 or Python 3.
Be careful not to compare against number values directly, because they can be different on different platforms. Instead, use the named constants in Python's standard library errno
module which will use the correct values for the run-time platform.
The Python 2 / 3 compatible way to except a FileNotFoundError
is this:
import errnotry: with open('some_file_that_does_not_exist', 'r'): passexcept EnvironmentError as e: if e.errno != errno.ENOENT: raise
Other answers are close, but don't re-raise if the error number doesn't match.
Using IOError
is fine for most cases, but for some reason os.listdir()
and friends raise OSError
instead on Python 2. Since IOError
inherits from OSError
it's fine to just always catch OSError
and check the error number.
Edit: The previous sentence is only true on Python 3. To be cross compatible, instead catch EnvironmentError
and check the error number.