Question
How to Create a Directory and Missing Parent Directories in Python
Question
How can I create a directory at a given path in Python and also create any missing parent directories along that path?
For example, in Bash, this is commonly done with:
mkdir -p /path/to/nested/directory
What is the Python way to do the same thing?
Short Answer
By the end of this page, you will understand how to create directories in Python, including nested parent directories that do not already exist. You will learn the most common approaches, how os.makedirs() and pathlib.Path.mkdir() work, what the exist_ok option does, and how to avoid common mistakes when working with filesystem paths.
Concept
Creating a directory is a basic filesystem operation. Sometimes you only need to create one folder, but often the full path includes parent folders that may not exist yet.
For example, if you want to create:
reports/2026/april/summary
Python cannot place summary inside april if reports, 2026, or april do not already exist. That is why Python provides ways to create the whole path at once.
The two main tools are:
os.makedirs()from theosmodulePath.mkdir()from thepathlibmodule
These let you create a directory and, if needed, create missing parent directories too.
This matters in real programming because many programs need to:
- create output folders before saving files
- prepare upload or cache directories
- initialize project structure
- ensure logs or temporary folders exist
Without this step, file-writing code often fails with errors like FileNotFoundError.
Mental Model
Think of a directory path like a set of nested boxes:
reportsis the outer box2026is a box inside itaprilis inside thatsummaryis the final box you want to create
If the outer boxes do not exist, you cannot place the inner box inside them.
Using normal single-directory creation is like saying, "Create only the final box." That fails if the larger boxes are missing.
Using makedirs() or parents=True is like saying, "Build every missing box along the way."
Syntax and Examples
Using os.makedirs()
import os
os.makedirs("path/to/nested/directory", exist_ok=True)
What this does
- creates
directory - creates
nestedif needed - creates
toif needed - creates
pathif needed - does not raise an error if the directory already exists because
exist_ok=True
Using pathlib.Path.mkdir()
from pathlib import Path
path = Path("path/to/nested/directory")
path.mkdir(parents=True, exist_ok=True)
What this does
parents=Truemeans create missing parent directoriesexist_ok=Truemeans do not fail if the directory already exists
Beginner-friendly example
Step by Step Execution
Consider this example:
from pathlib import Path
path = Path("data/raw/2026")
path.mkdir(parents=True, exist_ok=True)
print("Done")
Step-by-step
-
from pathlib import Path- Imports the
Pathclass for working with filesystem paths.
- Imports the
-
path = Path("data/raw/2026")- Creates a path object representing the directory you want.
- No directory is created yet.
-
path.mkdir(parents=True, exist_ok=True)- Python checks whether
dataexists. - If not, it creates
data. - Then it checks whether
data/rawexists. - If not, it creates
raw. - Then it checks whether
data/raw/2026exists. - If not, it creates
2026.
- Python checks whether
Real World Use Cases
Common practical uses
Saving generated files
A script that creates reports, exports CSV files, or writes images often needs to create an output folder first.
from pathlib import Path
report_dir = Path("exports/daily")
report_dir.mkdir(parents=True, exist_ok=True)
Application logging
An app may write logs into a nested folder such as var/log/myapp.
Upload storage
A web application may need user-specific folders before storing uploaded files.
Cache or temp data
Programs often create cache directories to store processed results.
Project setup scripts
A setup script can initialize folders like:
srctestsdocsbuild/output
Creating missing parent directories makes these scripts reliable and repeatable.
Real Codebase Usage
In real projects, developers usually do not create directories manually in many places. Instead, they use a small, consistent pattern.
Common pattern: ensure directory exists before writing
from pathlib import Path
file_path = Path("reports/2026/april/summary.txt")
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.write_text("Monthly summary")
This is very common because you usually care about writing a file, not just creating a folder.
Guard-style setup code
Programs often prepare required directories at startup:
from pathlib import Path
for folder in ["logs", "data/cache", "data/uploads"]:
Path(folder).mkdir(parents=True, exist_ok=True)
Configuration-driven paths
Applications may read output paths from config files or environment variables, then create them safely before use.
Error handling
Sometimes developers still wrap directory creation in try/except to handle permission problems or invalid paths:
from pathlib Path
:
Path().mkdir(parents=, exist_ok=)
OSError e:
()
Common Mistakes
1. Using mkdir() without creating parents
Broken example:
from pathlib import Path
Path("a/b/c").mkdir()
If a or a/b does not exist, this fails.
Fix:
Path("a/b/c").mkdir(parents=True, exist_ok=True)
2. Forgetting exist_ok=True
Broken example:
import os
os.makedirs("data/output")
This raises FileExistsError if the directory already exists.
Fix:
os.makedirs("data/output", exist_ok=True)
3. Creating the file path instead of the parent directory
Broken example:
pathlib Path
file_path = Path()
file_path.mkdir(parents=, exist_ok=)
Comparisons
os.makedirs() vs Path.mkdir()
| Feature | os.makedirs() | Path.mkdir() |
|---|---|---|
| Module | os | pathlib |
| Style | function-based | object-oriented |
| Creates parents | yes | yes, with parents=True |
| Ignore existing dir | exist_ok=True | exist_ok=True |
| Readability in modern code | good | often better |
Cheat Sheet
# Preferred modern style
from pathlib import Path
Path("a/b/c").mkdir(parents=True, exist_ok=True)
# Classic os style
import os
os.makedirs("a/b/c", exist_ok=True)
Key options
parents=True: create missing parent directoriesexist_ok=True: do not raise an error if the directory already exists
Common patterns
Create a nested folder
Path("logs/app/2026").mkdir(parents=True, exist_ok=True)
Ensure a file's parent folder exists
file_path = Path("exports/report.txt")
file_path.parent.mkdir(parents=True, exist_ok=True)
Important notes
Path.mkdir()withoutparents=Truefails if parent folders are missing.exist_ok=Truedoes not hide permission errors.
FAQ
How do I do mkdir -p in Python?
Use either:
os.makedirs(path, exist_ok=True)
or:
Path(path).mkdir(parents=True, exist_ok=True)
What does exist_ok=True mean?
It tells Python not to raise an error if the directory already exists.
What is the difference between os.mkdir() and os.makedirs()?
os.mkdir() creates one directory. os.makedirs() can create the full nested path, including missing parent directories.
Should I use os or pathlib?
Both work. For modern Python, pathlib is often easier to read and maintain.
Can directory creation still fail with exist_ok=True?
Yes. It can still fail because of permissions, invalid paths, or if part of the path is a file instead of a directory.
How do I create the parent folder for a file path?
Mini Project
Description
Build a small Python script that prepares an export folder and writes a text report into it. This demonstrates a very common real-world pattern: make sure the destination directory exists before saving a file.
Goal
Create a nested output directory safely, then write a file into that directory.
Requirements
- Create a nested directory such as
output/reports/weekly. - Do not fail if the directory already exists.
- Write a text file named
summary.txtinside that directory. - Print the final file path after writing the file.
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.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.