How to Check if a File or Directory Exists in Python
When working with files in Python, it's essential to verify whether a file or directory exists before performing operations on it. You might need to confirm a file is available before reading its contents, prevent overwriting an existing file, or ensure a target directory is in place before saving data. Skipping this check can lead to runtime errors like FileNotFoundError that crash your program unexpectedly.
In this guide, you'll learn four reliable methods to check if a file or directory exists in Python using the os.path and pathlib modules, complete with practical examples and best practices.
Overview of Available Methods
Python provides several built-in approaches to check for the existence of files and directories:
| Method | Purpose |
|---|---|
os.path.exists(path) | Checks if a file or directory exists |
os.path.isfile(path) | Checks if the path points specifically to a file |
os.path.isdir(path) | Checks if the path points specifically to a directory |
pathlib.Path.exists() | Object-oriented check for file or directory existence |
Using os.path.exists() to Check if a File or Directory Exists
The os.path.exists() method is the most general-purpose option. It returns True if the given path refers to an existing file or directory, and False otherwise.
Syntax:
os.path.exists(path)
- path: A string or path-like object representing a file system path.
- Returns:
Trueif the path exists,Falseotherwise.
Example:
import os
# Check if a directory exists
path_dir = '/usr/local/bin/'
print(os.path.exists(path_dir))
# Check if a file exists
path_file = '/home/User/Desktop/file.txt'
print(os.path.exists(path_file))
Output:
True
False
os.path.exists()Use this method when you don't care whether the path is a file or a directory: you just need to know if something exists at that location.
Using os.path.isfile() to Check if a File Exists
If you need to confirm that a path points specifically to a regular file (not a directory), use os.path.isfile(). This is useful when you want to distinguish between files and directories that might share similar naming patterns.
Syntax:
os.path.isfile(path)
- path: A string or path-like object representing a file system path.
- Returns:
Trueif the path is an existing regular file,Falseotherwise.
Example:
import os
# This is a file: returns True
path_file = '/home/User/Desktop/file.txt'
print(os.path.isfile(path_file))
# This is a directory, not a file: returns False
path_dir = '/home/User/Desktop/'
print(os.path.isfile(path_dir))
Output:
True
False
Common Mistake: Using os.path.exists() When You Need os.path.isfile()
A frequent error is using os.path.exists() to verify a file before reading it, only to accidentally open a directory path:
import os
path = '/home/User/Desktop/' # This is a directory, not a file
if os.path.exists(path):
# This will raise an error because the path is a directory
with open(path, 'r') as f:
content = f.read()
Output:
IsADirectoryError: [Errno 21] Is a directory: '/home/User/Desktop/'
Correct approach: use os.path.isfile() to ensure the path is actually a file:
import os
path = '/home/User/Desktop/'
if os.path.isfile(path):
with open(path, 'r') as f:
content = f.read()
else:
print("The path is not a valid file.")
Output:
The path is not a valid file.
Using os.path.isdir() to Check if a Directory Exists
The os.path.isdir() method checks whether a path points specifically to an existing directory. It also follows symbolic links, meaning if a symlink points to a directory, the method returns True.
Syntax:
os.path.isdir(path)
- path: A string or path-like object representing a file system path.
- Returns:
Trueif the path is an existing directory,Falseotherwise.
Example 1: Basic directory check
import os.path
# A file path: not a directory
path = '/home/User/Documents/file.txt'
print(os.path.isdir(path))
# A directory path
path = '/home/User/Documents/'
print(os.path.isdir(path))
Output:
False
True
Example 2: Symbolic links pointing to directories
os.path.isdir() resolves symbolic links and checks the target:
import os
# Create a directory
dirname = "tutorialreference"
os.mkdir(dirname)
# Create a symbolic link pointing to the directory
symlink_path = "/home/User/Desktop/tr"
os.symlink(dirname, symlink_path)
# Both the original directory and the symlink return True
print(os.path.isdir(dirname))
print(os.path.isdir(symlink_path))
Output:
True
True
If you need to check whether a path is a symbolic link itself (without following it), use os.path.islink() instead.
Using pathlib.Path.exists() to Check if a File or Directory Exists
The pathlib module, introduced in Python 3.4, provides a modern, object-oriented approach to file system paths. The Path.exists() method checks whether the path points to an existing file or directory.
Syntax:
from pathlib import Path
path = "your/path/to/something"
path_obj = Path(path)
path_obj.exists()
- Returns:
Trueif the file or directory exists,Falseotherwise.
Example:
from pathlib import Path
# Check a directory
dir_path = Path('/home/User/Desktop')
print(f"Directory exists? {dir_path.exists()}")
# Check a file
file_path = Path('/home/User/Desktop/file.txt')
print(f"File exists? {file_path.exists()}")
Output:
Directory exists? True
File exists? False
The pathlib module also provides its own is_file() and is_dir() methods for more specific checks:
from pathlib import Path
path = Path('/home/User/Desktop/file.txt')
print(f"Is a file? {path.is_file()}")
print(f"Is a directory? {path.is_dir()}")
print(f"Exists? {path.exists()}")
Output:
Is a file? True
Is a directory? False
Exists? True
If you're using Python 3.4 or later, pathlib is generally preferred over os.path because it provides a cleaner, more readable API. The Path objects also support path concatenation with the / operator, making path manipulation more intuitive.
Quick Comparison: os.path vs. pathlib
| Feature | os.path | pathlib |
|---|---|---|
| Style | Procedural (function-based) | Object-oriented |
| Python version | All versions | 3.4+ |
| Check existence | os.path.exists() | Path.exists() |
| Check file | os.path.isfile() | Path.is_file() |
| Check directory | os.path.isdir() | Path.is_dir() |
| Path manipulation | os.path.join() | / operator |
Conclusion
Python offers multiple reliable ways to check if a file or directory exists before performing operations on it:
os.path.exists(): for a general existence check (file or directory).os.path.isfile(): to confirm the path is specifically a file.os.path.isdir(): to confirm the path is specifically a directory.pathlib.Path.exists(): for a modern, object-oriented approach with additional methods likeis_file()andis_dir().
For new projects on Python 3.4+, prefer pathlib for its readability and cleaner API. For compatibility with older codebases, os.path remains a solid and battle-tested choice.
Keep in mind that checking for a file's existence and then operating on it introduces a race condition: the file could be created or deleted between the check and the operation. In critical scenarios, consider using a try/except block with FileNotFoundError instead.