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
path_dir = '/usr/local/bin/'
print(os.path.exists(path_dir))
path_file = '/home/User/Desktop/file.txt'
print(os.path.exists(path_file))Output:
True
FalseUsing 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
path_file = '/home/User/Desktop/file.txt'
print(os.path.isfile(path_file))
path_dir = '/home/User/Desktop/'
print(os.path.isfile(path_dir))Output:
True
FalseCommon 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):
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
path = '/home/User/Documents/file.txt'
print(os.path.isdir(path))
path = '/home/User/Documents/'
print(os.path.isdir(path))Output:
False
TrueExample 2: Symbolic links pointing to directories
os.path.isdir() resolves symbolic links and checks the target:
import os
dirname = "tutorialreference"
os.mkdir(dirname)
symlink_path = "/home/User/Desktop/tr"
os.symlink(dirname, symlink_path)
print(os.path.isdir(dirname))
print(os.path.isdir(symlink_path))Output:
True
TrueUsing 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
dir_path = Path('/home/User/Desktop')
print(f"Directory exists? {dir_path.exists()}")
file_path = Path('/home/User/Desktop/file.txt')
print(f"File exists? {file_path.exists()}")Output:
Directory exists? True
File exists? FalseThe 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? TrueQuick 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.