Question

How to Create a Directory and Missing Parent Directories in Python

pythonexceptionpathdirectoryoperating-system

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 the os module
  • Path.mkdir() from the pathlib module

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:

  • reports is the outer box
  • 2026 is a box inside it
  • april is inside that
  • summary is 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."

Take Quiz

Syntax and Examples

Using os.makedirs()

import os

os.makedirs("path/to/nested/directory", exist_ok=True)

What this does

  • creates directory
  • creates nested if needed
  • creates to if needed
  • creates path if 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=True means create missing parent directories
  • exist_ok=True means do not fail if the directory already exists

Beginner-friendly example

from pathlib import Path

output_dir = Path("output/images/2026")
output_dir.mkdir(parents=True, exist_ok=True)

print("Directory is ready.")

This code ensures the output/images/2026 folder exists before your program tries to save files there.

If you only want to create one directory

from pathlib import Path

Path("logs").mkdir()

This works only if the parent location already exists. If it does not, Python raises an error.

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

  1. from pathlib import Path

    • Imports the Path class for working with filesystem paths.
  2. path = Path("data/raw/2026")

    • Creates a path object representing the directory you want.
    • No directory is created yet.
  3. path.mkdir(parents=True, exist_ok=True)

    • Python checks whether data exists.
    • If not, it creates data.
    • Then it checks whether data/raw exists.
    • If not, it creates raw.
    • Then it checks whether data/raw/2026 exists.
    • If not, it creates 2026.
    • If the directory already exists, no error is raised because of exist_ok=True.
  4. print("Done")

    • Prints a success message after the directory is ready.

Result

After execution, the full directory path exists and can safely be used for saving files.

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:

  • src
  • tests
  • docs
  • build/output

Creating missing parent directories makes these scripts reliable and repeatable.

Take Quiz

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 import Path

try:
    Path("/restricted/app/data").mkdir(parents=True, exist_ok=True)
except OSError as e:
    print(f"Could not create directory: {e}")

exist_ok=True prevents errors for existing folders, but it does not prevent errors such as:

  • permission denied
  • invalid path
  • path points to a file instead of a directory

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:

from pathlib import Path

file_path = Path("reports/result.txt")
file_path.mkdir(parents=True, exist_ok=True)

This tries to create a directory named result.txt.

Fix:

file_path.parent.mkdir(parents=True, exist_ok=True)

4. Assuming this handles permission issues

Even correct code can fail:

from pathlib import Path

Path("/root/app").mkdir(parents=True, exist_ok=True)

If your program does not have permission, Python raises an OSError.

5. Mixing up strings and paths carelessly

Python supports both string paths and Path objects, but beginners sometimes mix them inconsistently. Pick one style and use it clearly. For modern Python code, pathlib is often easier to read.

Comparisons

os.makedirs() vs Path.mkdir()

Featureos.makedirs()Path.mkdir()
Moduleospathlib
Stylefunction-basedobject-oriented
Creates parentsyesyes, with parents=True
Ignore existing direxist_ok=Trueexist_ok=True
Readability in modern codegoodoften better
Works well with path operationsokayexcellent

Example comparison

import os
os.makedirs("data/output", exist_ok=True)
from pathlib import Path
Path("data/output").mkdir(parents=True, exist_ok=True)

Both are correct. Many modern Python codebases prefer pathlib because it combines path building and filesystem actions in one API.

mkdir() vs makedirs()

FunctionCreates one directoryCreates missing parents
os.mkdir()yesno
os.makedirs()yesyes
Path.mkdir()yesyes, with parents=True

Use single-directory creation when you know the parent already exists. Use recursive parent creation when the full path may not exist.

Take Quiz

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 directories
  • exist_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() without parents=True fails if parent folders are missing.
  • exist_ok=True does not hide permission errors.
  • Use file_path.parent when preparing to write a file.
  • pathlib is usually the cleanest choice in modern Python.

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?

Use the parent directory:

file_path.parent.mkdir(parents=True, exist_ok=True)

Does Python create directories automatically when writing a file?

No. If the parent directory does not exist, writing the file usually fails. You must create the directory first.

Take Quiz

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

  1. Create a nested directory such as output/reports/weekly.
  2. Do not fail if the directory already exists.
  3. Write a text file named summary.txt inside that directory.
  4. Print the final file path after writing the file.
Take Quiz

Keep learning

Related questions

View more