How to check if a file exists in Python
Use pathlib: Path('foo.txt').exists() or .is_file(). Prefer over os.path.exists — pathlib is the modern default.
from pathlib import Path
p = Path("data.csv")
if p.exists() and p.is_file():
print("found")
else:
print("missing").exists() returns True for files, directories, and symbolic links. .is_file() narrows to regular files only — safer if you want to distinguish 'file' from 'directory of the same name'.
The 'ask permission' pattern (check-then-open) has a TOCTTOU race: another process can delete the file between your check and your open. For opening the file, prefer the 'ask forgiveness' pattern: try opening it and catch FileNotFoundError.
os.path.exists still works and is fine for legacy code. For anything new, pathlib is cleaner and gives you an object you can immediately act on (.read_text(), .write_text(), .stat(), etc.).
Variations
Ask forgiveness (no race)
try:
with open("data.csv", encoding="utf-8") as f:
data = f.read()
except FileNotFoundError:
data = ""Preferred pattern when you're going to open the file anyway.
os.path (legacy)
import os
if os.path.isfile("data.csv"):
print("found")Same behaviour as Path.is_file().
Check for a directory
if Path("logs").is_dir():
print("logs dir exists")Use .is_dir() when the target should be a folder.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.