Python’s “open()” throws different errors for “file not found” – how to handle both exceptions?

In 3.3, IOError became an alias for OSError, and FileNotFoundError is a subclass of OSError. So you might try

except (OSError, IOError) as e:
   ...

This will cast a pretty wide net, and you can’t assume that the exception is “file not found” without inspecting e.errno, but it may cover your use case.

PEP 3151 discusses the rationale for the change in detail.

Leave a Comment