This article shows how a directory and all missing parents of this directory can be created in Python.
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.
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