How to create a nested directory in Python
This article shows how a directory and all missing parents of this directory can be created in Python.
This article shows how a directory and all missing parents of this directory can be created in Python.
#more
Use pathlib.Path.mkdir
¶
Since Python 3.5 the best and easiest way to create a nested directory is by using pathlib.Path.mkdir:
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
If parents is true, any missing parents of this path are created as needed (Make sure to have required permissions for this path).
If parents is false (the default), a missing parent raises FileNotFoundError.
If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.
If exist_ok is true, FileExistsError exceptions will be ignored, but only if the last path component is not an existing non-directory file.
Use os.path.makedirs
¶
For older Python versions os.path.makedirs can be used together with os.path.exists:
import os
if not os.path.exists(directory):
os.makedirs(directory)
Be aware that in rare cases a race condition can occur here – if the directory is created between the os.path.exists
and the os.makedirs
calls, the os.makedirs
will fail with an OSError. More information about this can be found here.
Use Pathlib to check if a file exists¶
The pathlib module is also very useful to check if a file or a directory exists in Python. You can read more about this in the following short article:
How to check if a file or directory exists in Python
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*