Create Parent Directories with Python
source link: https://www.devdungeon.com/content/create-parent-directories-python
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK