How do you create a directory along with all missing parent directories in Python? | A1Lab@MZeeshanM to PythonEnglish • 7 days ago

How do you create a directory along with all missing parent directories in Python?

message-square
0

Use Path.mkdir(parents=True, exist_ok=True) from Python’s built-in pathlib module (or os.makedirs(path, exist_ok=True)) to create a target directory along with any missing intermediate parent directories without raising an error if the directory already exists.

Basic Example

from pathlib import Path

# 1. Define a nested directory path where parent folders may not exist yet
target_dir = Path("projects/2026/analytics/reports")

# 2. Create the target directory and all missing parent directories safely
target_dir.mkdir(parents=True, exist_ok=True)

print(target_dir.exists())  # Output: True

Key Details & Parameters

  • parents=True: Tells Python to create any missing intermediate directories along the path (equivalent to mkdir -p in Unix/Linux shells). If parents=False (the default) and a parent folder is missing, Python raises a FileNotFoundError.
  • exist_ok=True: Prevents a FileExistsError if the target directory already exists. Note that if the path already exists as a regular file rather than a directory, exist_ok=True will still raise a FileExistsError to protect your file.
  • Creating parent folders before writing a file: A common pattern when saving output files to dynamic paths is calling .parent.mkdir() on the file path first:
    output_file = Path("logs/november/app.log")
    output_file.parent.mkdir(parents=True, exist_ok=True)
    output_file.write_text("Log started\n", encoding="utf-8")
    
  • Using os.makedirs() (string-based alternative): If you prefer working with plain string paths rather than Path objects, use os.makedirs():
    import os
    
    os.makedirs("projects/2026/analytics/reports", exist_ok=True)
    
  • Setting custom directory permissions (mode): Both Path.mkdir() and os.makedirs() accept an optional mode parameter (defaulting to 0o777, modified by the system’s umask), such as target_dir.mkdir(mode=0o755, parents=True, exist_ok=True) on Unix/Linux systems.

Comparison of Directory Creation Methods

Method Creates Missing Parents? Safe if Directory Exists? Return Type / Style
Path.mkdir(parents=True, exist_ok=True) Yes Yes Object-oriented (pathlib.Path)
os.makedirs(path, exist_ok=True) Yes Yes String-based (os module)
Path.mkdir() / os.mkdir(path) No (raises FileNotFoundError) No (raises FileExistsError) Single-level directory creation only