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:

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

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

def file_exists(filename):
        my_file = open(filename)
        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")
>>> os.path.exists("fake.txt")

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")

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()
>>> path.is_file()

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.

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!

Learn more about the course

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!