Lingua-e
Python

What is a OSError?

← Errors

OSError is the base class for operating system-related errors in Python. It is raised when a system call fails, such as file operations, process management, or network I/O. Many specific exceptions like FileNotFoundError and PermissionError are subclasses of OSError.

Why it happens

  • Attempting to open, rename, or delete a file that does not exist.
  • Trying to create a directory that already exists.
  • A disk I/O failure or hardware error occurs.
  • An invalid file descriptor is used in a low-level system call.

Examples

Python

Code that triggers the error

import os
os.rename("old.txt", "new.txt")

Error output

OSError: [Errno 2] No such file or directory: 'old.txt' -> 'new.txt'

How to fix it

Wrap OS operations in a try/except OSError block and inspect the errno attribute for the specific error code. Use pathlib for safer, more expressive file operations. Check preconditions (file existence, permissions) before performing the operation.

Fixed code

import os
from pathlib import Path

src = Path("old.txt")
if src.exists():
    src.rename("new.txt")
else:
    print("Source file not found")

Related errors

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free