OSError
PythonERRORI/O ErrorHIGH confidence

Operating system-related error

What this means

Raised when a system function returns a system-related error, including I/O failures like 'file not found' or 'disk full'. It's a base class for many more specific exceptions like `FileNotFoundError` and `PermissionError`.

Why it happens
  1. 1An underlying issue with the operating system, such as running out of file descriptors.
  2. 2Interacting with the filesystem in an invalid way, like trying to create a directory that already exists.
  3. 3Hardware errors, such as a disk failure or a network interface going down.
How to reproduce

This is a general error. A specific example is trying to create a directory that already exists, which raises a `FileExistsError`, a subclass of `OSError`.

trigger — this will error
trigger — this will error
import os
os.mkdir("existing_directory") # Assuming this directory already exists

expected output

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileExistsError: [Errno 17] File exists: 'existing_directory'

Fix 1

Catch specific subclasses instead of base `OSError`

WHEN You want to handle different OS-level errors in different ways.

Catch specific subclasses instead of base `OSError`
import os
try:
    os.mkdir("my_dir")
except FileExistsError:
    print("Directory 'my_dir' already exists.")
except PermissionError:
    print("Do not have permission to create 'my_dir'.")

Why this works

Catching more specific exceptions allows for more granular and appropriate error handling logic, rather than treating all OS errors the same.

Fix 2

Check for conditions before acting

WHEN You can prevent the error from happening in the first place.

Check for conditions before acting
import os
dir_path = "my_dir"
if not os.path.exists(dir_path):
    os.mkdir(dir_path)

Why this works

This 'Look Before You Leap' (LBYL) approach avoids the error by first checking if the condition that would cause it is true.

Code examples
Triggerpython
import os
os.mkdir("existing_dir")  # FileExistsError (subclass of OSError)
Handle with try/exceptpython
try:
    os.mkdir("my_dir")
except FileExistsError:
    pass  # already exists
except PermissionError as e:
    print(f"Permission denied: {e}")
Avoid with exist_okpython
import os
os.makedirs("my_dir", exist_ok=True)  # never raises FileExistsError
What not to do

Catching the base `OSError` and ignoring it

`OSError` can signify serious problems (like a full disk or hardware failure) that should almost never be ignored silently.

Sources
Official documentation ↗

cpython/Objects/exceptions.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors