Skip to main content

How to Check Whether a File or Folder Exists in Python with pathlib

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Before a script reads a file or writes into a folder, it often has to know whether that file or folder is there. Path.is_file() and Path.is_dir() answer that, and they also tell a file from a folder. This guide checks a file, a folder and a name that doesn't exist, with real output from Python 3.15.2.

Syntax​

Syntax
<path>.is_file()
<path>.is_dir()
PartWhat it means
<path>A Path object, such as Path("plan.txt")
.is_file()True when the path is an existing file
.is_dir()True when the path is an existing folder

Python's pathlib reference: "Return True if the path points to a regular file. False will be returned if the path is invalid, inaccessible or missing, or if it points to something other than a regular file."

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

The project folder holds a file, plan.txt, and a folder, reports. There's no missing.txt.

check_paths.py
from pathlib import Path

for name in ["plan.txt", "reports", "missing.txt"]:
path = Path(name)
print(name, "| file:", path.is_file(), "| folder:", path.is_dir())

The check_paths.py script in a macOS-style code window: for plan.txt, reports and missing.txt, it prints whether each is a file and whether it's a folder.

Step 2: Run It​

Terminal
uv run python check_paths.py
Output
plan.txt | file: True | folder: False
reports | file: False | folder: True
missing.txt | file: False | folder: False

The script's output in a terminal: plan.txt is a file, reports is a folder, and missing.txt is neither.

plan.txt is a file, reports is a folder, and missing.txt is neither, so both checks are False.

Common Mistakes​

MistakeWhat happensDo this instead
Checking is_file() on a folder you're about to write intoIt's False for folders, as reports showsUse is_dir() for folders
Treating False as "missing"False also means "not that kind": reports isn't a file but existsCheck the kind you need

Troubleshooting​

SymptomLikely causeFix
is_file() is False for a file you can seeA relative path, looked up in the folder you ran the script fromRun it from the file's folder, or build the path from the script's folder

FAQ​

What about exists()?​

Path.exists() is True for files and folders alike: for plan.txt, reports and missing.txt it gave True, True and False. Use it when either is fine.

Do the checks raise an error for a missing path?​

No: as missing.txt shows, they return False.

Conclusion​

is_file() was True only for plan.txt, and is_dir() only for reports; for missing.txt, both were False.

Additional Resources​

  • pathlib — is_file, is_dir, exists and the other checks.