directories
recursive
file system
programming
duplicate

How can I create directories recursively?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Creating directories recursively means creating a target directory and any missing parent directories in its path. Most modern tools have a built-in way to do this, so the real question is usually which API fits your language or environment.

The Shell Answer: mkdir -p

On Unix-like systems, the standard command is:

bash
mkdir -p /path/to/project/data/output

The -p flag tells mkdir to create missing parent directories as needed and to avoid failing if the path already exists.

That makes it the standard shell solution for scripts and one-off setup commands.

Python: os.makedirs

In Python, the traditional function is os.makedirs.

python
import os

os.makedirs("project/data/output", exist_ok=True)

The exist_ok=True part is important. Without it, Python raises an error if the directory already exists.

This is the direct equivalent of the shell's mkdir -p behavior.

Python: pathlib.Path.mkdir

If you prefer modern path handling, pathlib is usually cleaner.

python
from pathlib import Path

Path("project/data/output").mkdir(parents=True, exist_ok=True)

This is often the most readable Python solution because the path object and the creation logic live together naturally.

For new Python code, many developers prefer this over os.makedirs.

Java: Files.createDirectories

In Java, the usual answer is Files.createDirectories.

java
1import java.io.IOException;
2import java.nio.file.Files;
3import java.nio.file.Path;
4import java.nio.file.Paths;
5
6public class Main {
7    public static void main(String[] args) throws IOException {
8        Path path = Paths.get("project/data/output");
9        Files.createDirectories(path);
10    }
11}

This creates all missing parent directories and does not fail if the directory already exists.

Why Recursive Creation Is Better Than Manual Step-By-Step Creation

You could create each path segment manually, but that is unnecessary and fragile.

For example, this is worse than using the built-in recursive API:

  • more code
  • more edge cases
  • more race conditions in concurrent environments

Recursive creation APIs exist precisely so you do not have to reimplement that logic yourself.

Handling Existing Paths

One subtle question is what should happen if the path already exists.

Most recursive directory helpers have an option or default behavior that tolerates existing directories. That is usually what you want in setup code, deployment scripts, and idempotent automation.

The more dangerous case is when a non-directory file already exists at that path. Then creation should still fail, because the filesystem structure is not what you expected.

A Small Reusable Python Helper

python
1from pathlib import Path
2
3
4def ensure_dir(path: str) -> None:
5    Path(path).mkdir(parents=True, exist_ok=True)
6
7
8ensure_dir("project/data/output")

This makes higher-level application code easier to read and keeps directory creation idempotent.

Relative Versus Absolute Paths

The creation logic works the same way for both relative and absolute paths, but you should still know which one you are using.

Relative paths depend on the current working directory. That is fine in a script you control, but it can be a source of bugs in larger applications or test runs.

When correctness matters, resolve the path explicitly before creating it.

Common Pitfalls

The most common mistake is forgetting the recursive option and then getting a failure because the parent directory does not exist.

Another mistake is omitting the "already exists" behavior in code that should be idempotent.

Developers also sometimes assume a path collision with an existing file will be handled harmlessly. It will not; and it should not.

Finally, be careful with relative paths in long-running applications or background jobs. The current working directory may not be what you think.

Summary

  • In the shell, use mkdir -p.
  • In Python, use os.makedirs(..., exist_ok=True) or Path.mkdir(parents=True, exist_ok=True).
  • In Java, use Files.createDirectories(...).
  • Recursive directory creation is better than manually creating each parent path segment.
  • Make the operation idempotent when repeated execution is expected.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions