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.
open("missing.txt") # FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
Try it
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.
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
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
OSErrorfor 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
errnoagainsterrno.ENOENTrather than a literal such as 2, and never match on the message. - Use
withso 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 usepathlib. exist_ok=TrueavoidsFileExistsErrorforos.makedirs()andPath.mkdir(). The mode"x"inopen()asks for the error on purpose.- Encoding problems are not
OSError. Decoding failures raiseUnicodeDecodeError, a subclass ofValueError. PermissionErroralso appears when opening a directory on Windows or writing to a read-only file.- Since Python 3.3 the old distinct
IOError,socket.errorandselect.errorwere merged intoOSError; writeOSErrorin new code. - Network failures are
OSErrortoo: a refused connection raisesConnectionRefusedError, a slow oneTimeoutError.
Related
open(),open()modes and encodings,withos,pathlib, the exception hierarchy- Lessons: Files, Exceptions