Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Exceptions

Python OSError and FileNotFoundError

Reference for Python OSError and its subclasses FileNotFoundError, PermissionError and FileExistsError: errno, strerror, filename and safe file handling.

OSError is raised when an operation that talks to the operating system fails: opening or deleting a file, creating a directory, listing a folder, using a socket. It carries the system's error number and message.

Python maps the most common error numbers to subclasses, so you rarely need to look at the number: FileNotFoundError, FileExistsError, PermissionError, IsADirectoryError, NotADirectoryError, TimeoutError, ConnectionError (with ConnectionRefusedError and friends) and a few more. IOError, EnvironmentError and socket.error are old aliases of OSError.

Python
open("missing.txt")   # FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'

Try it

Python FileNotFoundError and its fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Subclasses and safe file handling

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
try:
    with open(path) as f:
        data = f.read()
except FileNotFoundError:
    ...
except PermissionError:
    ...
except OSError as error:
    print(error.errno, error.strerror, error.filename)
Attribute Description
errno The numeric error code (compare with constants from the errno module, such as errno.ENOENT).
strerror The operating system's description of the error.
filename The path involved, or None.
filename2 The second path for two-path operations such as os.rename().

Common subclasses: FileNotFoundError (ENOENT), FileExistsError (EEXIST), PermissionError (EACCES, EPERM), IsADirectoryError, NotADirectoryError, TimeoutError, ConnectionRefusedError, ConnectionResetError, BrokenPipeError, BlockingIOError, InterruptedError.

Usage notes

  • Catch the specific subclass first, then OSError for everything else. Subclass clauses must come before the base class, or they will never run.
  • Do not check then act. if os.path.exists(p): open(p) has a race: the file can vanish between the two calls. Just try the operation and handle the exception.
  • Error numbers differ between platforms, and so do the message texts. Compare errno against errno.ENOENT rather than a literal such as 2, and never match on the message.
  • Use with so the file is closed even when an error occurs; see the context manager reference page.
  • Relative paths are resolved against the current working directory, which is the most common reason a file that "is right there" cannot be found. Build paths from __file__ or use pathlib.
  • exist_ok=True avoids FileExistsError for os.makedirs() and Path.mkdir(). The mode "x" in open() asks for the error on purpose.
  • Encoding problems are not OSError. Decoding failures raise UnicodeDecodeError, a subclass of ValueError.
  • PermissionError also appears when opening a directory on Windows or writing to a read-only file.
  • Since Python 3.3 the old distinct IOError, socket.error and select.error were merged into OSError; write OSError in new code.
  • Network failures are OSError too: a refused connection raises ConnectionRefusedError, a slow one TimeoutError.