site logo

Ask. Code. Learn. Grow with the Developer Community.


Category: (All)
❮  Go Back

Python Create Directory with Missing Parents (mkdir -p Equivalent)

How do I create a directory at a given path, including any missing parent directories, similar to mkdir -p /path/to/dir in Bash?

Python Create Directory with Missing Parents mkdir -p Equivalent

coldshadow44 on 2025-10-13





Make a comment


Showing comments related to this post.

_

2025-10-14

Modern Python (3.5+) – Using pathlib

The pathlib module provides an elegant, object-oriented way:


from pathlib import Path

Path("/my/directory").mkdir(parents=True, exist_ok=True)
  1. parents=True: Automatically creates any missing parent directories.
  2. exist_ok=True: Prevents an error if the directory already exists.

Python 3.2+ – Using os.makedirs

import os

os.makedirs("/my/directory", exist_ok=True)
  1. Equivalent to mkdir -p.
  2. exist_ok=True avoids FileExistsError if the directory already exists.

Python <3.2 – Safe Approach

Older versions don’t have exist_ok, so you need to handle the exception manually:

import os, errno

directory = "/my/directory"

try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
# Re-raise exception if it's not "directory already exists"
raise
  1. This handles the race condition where another process may create the directory between checks.

Best Practice

  1. Use pathlib.Path.mkdir for modern Python (3.5+): clean, readable, and safe.
  2. Use os.makedirs(exist_ok=True) if you prefer os functions.
  3. Avoid os.path.exists checks before creating directories; it can lead to race conditions.

This approach works reliably across different Python versions and ensures nested directories are created safely.




Member's Sites: