Check whether a file or path exists

suggest change

Employ the EAFP coding style and try to open it.

import errno

try:
    with open(path) as f:
        # File exists
except IOError as e:
    # Raise the exception if it is not ENOENT (No such file or directory)
    if e.errno != errno.ENOENT:
        raise
    # No such file or directory

This will also avoid race-conditions if another process deleted the file between the check and when it is used. This race condition could happen in the following cases:

import os
os.path.isfile('/path/to/some/file.txt')
import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
    ...

To check whether a given path exists or not, you can follow the above EAFP procedure, or explicitly check the path:

import os
path = "/home/myFiles/directory1"

if os.path.exists(path):
    ## Do stuff

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents