Create Parent Directories with Python


A common task when working with systems is to create directories. There can be times when you need to create a directory several layers deep. The normal mkdir commands only let you create a single level at a time. This example will show you how to create multiple directory levels at once, the equivalent of running mkdir -p in the Bash shell.

Method 1) os.makedirs()

The easiest way to make multiple directory levels is with os package function os.makedirs() like this:

import os

Method 2) pathlib.Path.mkdir()

You can also use pathlib package to create multiple directories like this:

from pathlib import Path

target_path = Path('/path/to/new/dirs')
target_path.mkdir(parents=True, exist_ok=True)


After following this guide you should know how to create a new directory in Python 3 even if the children directories do not exist.