Michael Sohnen
Michael Sohnen

Reputation: 980

Python "With" command detect nonexistent file

If I want to use the "with" command in python to open a file, how can I detect a file being nonexistent and handle that case accordingly? (for example, if the filename is inputted by user, and the program needs to check if a file with the filename exists) Also, How do I handle failures to open a file, for example a permission error or an error due to a corrupted file, using a python "With" statement?

Upvotes: 0

Views: 1949

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155506

You can either wrap the whole block in a try block and catch OSError (the parent of all I/O and permission related errors in Python 3), or if you need to be absolutely sure it came from the open, and not another call in the block, open outside the with block, and immediately with it after verifying success.

Approach number 1:

try:
    with open(...) as f:
        ...
except OSError:
    ... handle error ...

or to only catch from the open:

try:
    f = open(...)
except OSError:
    ... handle error ...
else:
    # When the open succeeds, this is the very next thing executed, so
    # race window for stuff like Ctrl-C interrupting is tiny
    with f:
        ...

If you only want to catch a subset of OSError subclasses, you can explicitly catch them one by one, or for uniform handling, catch a tuple of all recognized errors, e.g., to only catch non-existent file, is a directory, or permission related errors, while allowing other errors to bubble up, you could change:

except OSError:

to:

except (FileNotFoundError, IsADirectoryError, PermissionError):

Upvotes: 1

Related Questions