Sometimes, we want to safely create a nested directory in Python.
In this article, we’ll look at how to safely create a nested directory in Python.
How to safely create a nested directory in Python?
To safely create a nested directory in Python, we can use the Path instance’s mkdir method.
For instance, we write:
from pathlib import Path
Path("./my/directory").mkdir(parents=True, exist_ok=True)
We invoke the Path constructor with the path of the directory we want to create.
Then we set parents and exist_ok to True so that it’ll create the nested directory without the parent directory being present.
Conclusion
To safely create a nested directory in Python, we can use the Path instance’s mkdir method.