Python Principles

Checking if a file exists

Sometimes you need to check if a file exists on your file system. Here are different ways to accomplish this.

Using exceptions

The most Pythonic way to do this is to simply try accessing the file, while catching any exceptions that occur in case the file doesn't actually exist. For example:

try:
    my_file = open(filename)
except IOError:
    # file didn't exist (or other issues)
    pass

You can wrap this in a function, although that somewhat defeats the purpose of using this approach:

def file_exists(filename):
    try:
        my_file = open(filename)
        my_file.close()
        return True
    except IOError:
        # file didn't exist (or other issues)
        return False

Using os.path

The os module has a path component with an exists function:

>>> import os
>>> os.path.exists("test.txt")
True
>>> os.path.exists("fake.txt")
False

Note, however, that this returns True for files and directories, so you can instead use isfile if only files should be accepted:

>>> os.path.isfile("test.txt")
True

Using pathlib

Python 3 includes a module named pathlib that lets you define a Path. Such a Path has an exists method you can use:

>>> import pathlib
>>> path = pathlib.Path("test.txt")
>>> path.exists()
True
>>> path.is_file()
True

A note on race conditions

Even though you check that a file exists, there is no guarantee that the file won't be removed immediately after your check was performed. That's why opening the file inside a try/catch block is preferred; that way, even if the file is removed, you still have a handle to it.

Want to get better at Python?

Try our practical beginner lessons, or test your skills with our challenges.

View Lessons Try Challenges