Python Language Files & Folders I/O Check whether a file or path exists

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Python Language Question?