Create Parent Directories with Python

Advertisement

Advertisement

Introduction

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
os.makedirs('/path/to/new/dirs')

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)

Conclusion

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

References

Advertisement

Advertisement