Python › File I/O & Context Managers

How do you check whether a file or directory exists before operating on it, using pathlib?

Intermediate

Answer

Path.exists() returns True if the path exists at all (file or directory); Path.is_file() and Path.is_dir() narrow the check to specifically a regular file or a directory respectively, letting you branch logic based on exactly what kind of filesystem entry is present.
from pathlib import Path

p = Path("data.txt")
if p.exists() and p.is_file():
    content = p.read_text()
else:
    print("File not found")
Real-world example Checking whether a configuration file exists before attempting to read it, falling back to defaults if it doesn't.

Common follow-ups: Is there a race condition risk between checking p.exists() and later opening the file, and how would EAFP-style code avoid it?