W3docs

mkdir -p functionality in Python

The os.makedirs() function in Python can be used to create a directory with the -p option, which will create the entire directory path, including any missing parent directories.

The os.makedirs() function in Python creates a directory and all missing parent directories in the specified path. To prevent an error when the directory already exists, use the exist_ok=True parameter. Here is a code snippet:

Creating a directory with missing parent directories

import os

directory_path = '/path/to/directory'

os.makedirs(directory_path, exist_ok=True)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

The exist_ok parameter is set to True, so if the directory already exists, os.makedirs() will not raise an error. If you want to raise an error if the directory already exists, set exist_ok to False.

Handling existing directories with exist_ok=False

import os

directory_path = '/path/to/directory'

os.makedirs(directory_path, exist_ok=False)

This will create the directory if it does not exist and raise a FileExistsError if it already exists.

For a more modern approach, you can also use pathlib.Path.mkdir(parents=True, exist_ok=True).