Question
How can I check whether a directory exists in Python?
Short Answer
You will learn how to distinguish an existing directory from a file or missing path in Python. You will use the modern pathlib approach, understand the older os.path alternative, and apply safe checks before reading or creating folders.
Concept
A filesystem path can point to several different things:
- A directory (folder)
- A file
- A symbolic link
- Nothing, because the path does not exist
To check specifically for a directory, use a directory-aware method rather than only checking whether the path exists.
In modern Python, pathlib.Path.is_dir() is the clearest choice. It returns True only when the path exists and is a directory.
from pathlib import Path
reports = Path("reports")
if reports.is_dir():
print("The reports directory exists.")
else:
print("The reports directory does not exist.")
This matters because a path named reports could exist as a regular file. A general existence check would not tell you whether it is safe to use that path as a folder.
Mental Model
Think of a path as an address.
path.exists()asks: “Is there anything at this address?”path.is_file()asks: “Is there a file at this address?”path.is_dir()asks: “Is there a folder at this address?”
If your code needs to store several files inside an address, you need a folder, so is_dir() asks the precise question.
Syntax and Examples
Use Path.is_dir() from the built-in pathlib module.
from pathlib import Path
folder = Path("data/uploads")
if folder.is_dir():
print(f"{folder} is an existing directory")
else:
print(f"{folder} is missing or is not a directory")
Path("data/uploads") creates a path object. It does not create the folder. Calling folder.is_dir() checks the filesystem and returns a Boolean value.
You can also use an absolute path:
from pathlib import Path
folder = Path("/var/app/uploads")
print(folder.is_dir())
Older os.path syntax
Many existing projects use os.path.isdir():
import os
if os.path.isdir("data/uploads"):
()
Step by Step Execution
Consider this code:
from pathlib import Path
export_dir = Path("exports")
if not export_dir.is_dir():
export_dir.mkdir(parents=True)
print("Ready to save files in", export_dir)
Step by step:
Path("exports")represents a path namedexportsrelative to the current working directory.export_dir.is_dir()checks whether that path currently exists as a directory.notreverses the result. If the directory is absent, the condition isTrue.mkdir(parents=True)createsexports.parents=Truealso creates missing parent directories if needed.- The final
printruns whether the directory already existed or was just created.
For repeated or concurrent setup code, prefer this shorter creation pattern:
export_dir.mkdir(parents=True, exist_ok=True)
It creates the directory when needed and does not fail merely because the directory already exists.
Real World Use Cases
Directory checks are useful whenever code depends on local storage:
- File uploads: Verify that an upload folder is available before saving user files.
- Reports and exports: Create or validate a
reports/directory before writing CSV, PDF, or JSON output. - Application configuration: Check whether a configuration directory exists before loading settings files.
- Data pipelines: Confirm that an input folder exists before scanning it for source files.
- Backups: Ensure a backup destination is a directory before copying data.
- Command-line tools: Give a clear error when a user supplies a path that does not point to a folder.
Real Codebase Usage
In production code, developers often validate a path early and produce a useful error message.
Guard clause for required input
from pathlib import Path
def load_csv_files(input_dir: str) -> list[Path]:
folder = Path(input_dir)
if not folder.is_dir():
raise ValueError(f"Input directory does not exist: {folder}")
return list(folder.glob("*.csv"))
The guard clause prevents the rest of the function from running with an invalid directory.
Ensure an output directory exists
from pathlib import Path
def save_report(content: str) -> Path:
output_dir = Path("output")
output_dir.mkdir(parents=True, exist_ok=True)
report_path = output_dir / "report.txt"
report_path.write_text(content, encoding="utf-8")
return report_path
For output locations your program owns, creating the directory is often more useful than checking first. exist_ok=True handles the normal “already exists” case.
Common Mistakes
Using exists() when a directory is required
This code accepts both files and directories:
from pathlib import Path
path = Path("settings")
if path.exists():
print("Ready")
If settings is a file, printing “Ready” may be incorrect. Use is_dir() when your code requires a folder.
if path.is_dir():
print("Ready")
Comparing a method instead of calling it
Broken code:
from pathlib import Path
folder = Path("data")
if folder.is_dir:
print("Directory exists")
folder.is_dir is the method itself, which is truthy. Call it with parentheses:
if folder.is_dir():
print("Directory exists")
Comparisons
| Check | Returns True when | Best use |
|---|---|---|
Path(path).exists() | A file, directory, or other filesystem entry exists | You only need to know whether anything exists there |
Path(path).is_dir() | The path exists and is a directory | You need a folder |
Path(path).is_file() | The path exists and is a regular file | You need a file |
os.path.exists(path) | Any filesystem entry exists | Maintaining older os.path code |
os.path.isdir(path) | The path exists and is a directory | Maintaining older os.path code |
Cheat Sheet
from pathlib import Path
folder = Path("data")
folder.exists() # True for a file or directory
folder.is_dir() # True only for an existing directory
folder.is_file() # True only for an existing file
folder.mkdir() # Create one directory
folder.mkdir(parents=True) # Also create missing parent directories
folder.mkdir(parents=True, exist_ok=True) # Create if absent; no error if present
import os
os.path.exists("data") # File or directory exists
os.path.isdir("data") # Directory exists
os.path.isfile("x.txt") # File exists
Rules:
- Prefer
Path.is_dir()when you specifically require a directory. - A
Pathobject does not create anything until you call an operation such asmkdir(). - Use
exist_ok=Truewhen creating a directory that may already exist. - Handle
OSErrorfor operations where permissions or filesystem changes matter.
FAQ
Does Path.is_dir() return False if the folder does not exist?
Yes. It returns False when the path is missing and when the path exists but is not a directory.
Does Path.exists() check whether a path is a directory?
No. It returns True for both files and directories. Use is_dir() to require a directory.
What is the recommended way to check for a directory in Python?
Use Path(path).is_dir() from pathlib in new code. It is clear and works across supported operating systems.
How do I create a directory only if it does not exist?
Use Path("folder").mkdir(parents=True, exist_ok=True). It creates missing directories and does not raise an error if the target directory already exists.
Is os.path.isdir() still valid in Python?
Yes. It is fully valid and is common in older codebases. pathlib is generally preferred for new code because its path operations are easier to read.
Can a directory check fail because of permissions?
It can. Filesystem access may be affected by permissions, unavailable drives, or other operating-system errors. Handle around critical filesystem operations.
Mini Project
Description
Build a small report-saving utility. It accepts a report name and text, makes sure an output directory is available, and saves the text as a .txt file. This reflects a common task in scripts that generate logs, exports, or reports.
Goal
Create an output directory when necessary and save a report file inside it.
Requirements
Use pathlib.Path for all path operations.
Ensure an output directory exists before writing the file.
Save a report as daily_report.txt.
Print the path of the saved report.
Read the saved file and print its contents.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.