Python, how to check if a file or directory exists

By

Learn how to check if a file or directory exists in Python using the os.path.exists() method, which returns True if the path exists and False if it does not.

~~~

The os.path.exists() method provided by the os standard library module returns True if a file exists, and False if not.

Here is how to use it:

import os

filename = '/Users/flavio/test.txt'

exists = os.path.exists(filename)

print(exists) # True

os.path.exists() says yes to anything at that path, whether it’s a file, a directory, or a symbolic link. So a True here doesn’t promise you a file you can read.

File or directory?

When you need to know which kind of thing is there, use the more specific checks:

import os

os.path.isfile('/Users/flavio/test.txt') # True if it's a file
os.path.isdir('/Users/flavio/photos') # True if it's a directory

isfile() returns False for a directory, and isdir() returns False for a file. Reach for these instead of exists() whenever the difference matters.

The pathlib way

Newer code tends to use pathlib, which wraps paths in objects and reads a bit more naturally:

from pathlib import Path

path = Path('/Users/flavio/test.txt')

path.exists() # True
path.is_file() # True
path.is_dir() # False

Both approaches do the same job. Pick whichever fits the rest of your code.

Watch out for the race condition

There’s a classic trap with checking existence before acting on a file. Between the moment you check and the moment you open the file, something else could delete or create it. The check passes, then the open fails anyway:

import os

if os.path.exists('/Users/flavio/test.txt'):
    open('/Users/flavio/test.txt') # might still fail

When your goal is to read or write the file, skip the check and just try the operation, catching the error if it fails:

try:
    with open('/Users/flavio/test.txt') as f:
        data = f.read()
except FileNotFoundError:
    print('File not found')

This is the “easier to ask forgiveness than permission” style, and it’s the safer choice when you’re about to touch the file. Keep os.path.exists() for cases where you only want to report whether a path is there, not immediately open it.

Tagged: Python · All topics
~~~

Related posts about python: