How to Check If a File Exists in Python
Before attempting to read from or write to a file in Python, it is crucial to verify its existence. Trying to access a non-existent file will raise a FileNotFoundError, crashing your script. Python provides robust tools for this, primarily via the classic os.path module and the modern pathlib object-oriented library.
This guide explains absolute versus relative paths and demonstrates two reliable methods for checking file existence.
Understanding File Paths (Absolute vs. Relative)
A file path tells the computer where a file is located.
- Absolute Path: The full address starting from the root (e.g.,
/home/user/project/data.txtorC:\Users\Name\data.txt). It works regardless of where your script is running. - Relative Path: The address relative to the Current Working Directory (e.g.,
data.txtor../data.txt).
import os
# Get current working directory (CWD)
cwd = os.getcwd()
print(f"Current Directory: {cwd}")
filename = "my_file.txt"
# Creating an absolute path
abs_path = os.path.join(cwd, filename)
print(f"Absolute Path: {abs_path}")
Method 1: Using os.path.exists() (Legacy)
The standard way to check for a file or directory in older Python code is using the os.path module. It returns True if the path exists (whether it's a file or a folder) and False otherwise.
import os
filename = "my_file.txt"
# ✅ Correct: Check existence
if os.path.exists(filename):
print(f"'{filename}' exists.")
else:
print(f"'{filename}' does not exist.")
# To be more specific (Check if it is a FILE, not a directory)
if os.path.isfile(filename):
print("It is definitely a file.")
Method 2: Using pathlib.Path.exists() (Modern)
Introduced in Python 3.4, pathlib offers an object-oriented approach. It is generally preferred for new projects because path objects are easier to manipulate (e.g., joining paths with /) and work consistently across operating systems.
from pathlib import Path
# Create a Path object
file_path = Path("my_file.txt")
# ✅ Correct: Object-oriented check
if file_path.exists():
print(f"'{file_path}' exists.")
# Specific check for file vs directory
if file_path.is_file():
print("It is a file.")
elif file_path.is_dir():
print("It is a directory.")
else:
print(f"'{file_path}' does not exist.")
pathlib handles operating system differences (like / vs \ separators) automatically, making your code more portable.
Conclusion
To check if a file exists in Python:
- Use
pathlib.Path(path).exists()for modern, readable, object-oriented code. - Use
os.path.exists(path)if working with legacy codebases. - Understand Paths: Remember that relative paths depend on where you run the script from (
os.getcwd()).