A Python file exists check is easiest with pathlib. To check if file exists in Python, create a Path object and call exists(). This works with both relative and absolute paths.
Use a pre-check when you need to choose a response for a missing path. When you immediately need to open the file, catch FileNotFoundError as well, because a path can change after the check.
Python file existence: check a path with pathlib
Import Path, then call exists() on the path you want to test:
from pathlib import Path
relative_path = Path(“reports/today.txt”)
absolute_path = Path(“/var/data/reports/today.txt”)
if relative_path.exists():
print(“The path exists”)
Path(“reports/today.txt”) is a relative path. Python resolves it against the process’s current working directory, which may differ from the directory containing your script. Use Path.cwd() to see that directory:
print(Path.cwd())
An absolute path identifies its location from the filesystem root, such as /var/data/reports/today.txt on Linux and macOS. Windows paths can use a raw string such as Path(r”C:\data\reports\today.txt”).
How do you distinguish files and directories?
exists() returns True for both files and directories. Use is_file() when the path must identify a regular file, and is_dir() when it must identify a directory:
path = Path(“reports/today.txt”)
if path.is_file():
print(“A file is available”)
elif path.is_dir():
print(“A directory is available”)
else:
print(“The path is missing”)
For a missing path, all three methods return False. A directory makes exists() and is_dir() true, but is_file() false. A file produces the opposite file-versus-directory result.
What are the os.path equivalents?
The older os.path functions provide the same basic tests and accept string paths:
import os
path = “reports/today.txt”
os.path.exists(path)
os.path.isfile(path)
os.path.isdir(path)
Use os.path.exists() for either type, os.path.isfile() for a file, and os.path.isdir() for a directory. os.path.abspath(path) converts a relative path to an absolute string. For new code, pathlib usually keeps path construction and file operations more readable.
What if a file disappears after the check?
An existence check is not a guarantee that the path will still exist when you use it. Another process can delete, replace, or rename the file between exists() and open(). This check-then-use race can also occur if a directory in the path changes.
For actual file access, open the path and handle the failure directly. This is how to check if a file exists while safely attempting to read it:
try:
with path.open(“r”, encoding=”utf-8″) as file:
contents = file.read()
except FileNotFoundError:
contents = “”
Use exists() for validation or user-facing messages, but rely on the exception when opening the file is the operation that matters.
