EnvironmentError
EnvironmentError: [Errno 2] No such file or directory
Traceback
Traceback (most recent call last):
File "main.py", line 4, in <module>
print("caught")
EnvironmentError: [Errno 2] No such file or directoryWhat causes this error
An OS-level error occurred. EnvironmentError is a legacy alias for OSError maintained for backward compatibility with Python 2 code.
How to fix it
Use OSError instead of EnvironmentError in new code. Catch specific subclasses like FileNotFoundError and PermissionError. When updating legacy code, EnvironmentError can be directly replaced with OSError.
Code that causes this error
try:
open("/nonexistent")
except EnvironmentError:
print("caught")Fixed code
try:
open("/nonexistent")
except FileNotFoundError:
print("File not found")
except OSError as e:
print(f"OS error: {e}")About EnvironmentError
EnvironmentError is a legacy alias for OSError. In Python 3.3+, EnvironmentError, IOError, and WindowsError were all merged into a single OSError class. They still exist as names for backward compatibility, but they are all the same class — `EnvironmentError is OSError` evaluates to True.
Old code that catches EnvironmentError works fine in Python 3, but new code should use OSError directly. The exception hierarchy under OSError includes FileNotFoundError, PermissionError, IsADirectoryError, ConnectionError, TimeoutError, and other specific exception classes, which were added in Python 3.3 to replace the old pattern of catching OSError and checking the errno attribute. When maintaining legacy codebases, you can safely replace EnvironmentError with OSError without changing any behavior.
Common scenarios
Running scripts without sufficient file system permissions
Connecting to servers that are not running or are unreachable
Installing Python packages without proper environment setup
Running out of disk space or file descriptors during I/O operations