Python Language Check whether a file or path exists


Example

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:

  • Using the os module:

    import os
    os.path.isfile('/path/to/some/file.txt')
    
Python 3.x3.4
  • Using pathlib:

    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