How To Safely Create Nested Directories in Python
Working with file systems can be tricky because there is an element of uncertainty
Creating nested directories, especially from an absolute path, is precarious because the success of the command relies on the parent directories existing to be nested within.
The pathlib library and its .mkdir() method offer a technique to safely create a nested directory.
We begin by importing the Path class from pathlib.from pathlib import Path
When creating the Path object, include the directory path to be created.p = Path("/nested/directory")
Next, we’ll use the .mkdir() method to create the directory.p.mkdir()
This will work, assuming the directory does not exist.
However, we need a safe mechanism to create the directory without causing exceptions and errors. To do this, let’s add the exist_ok flag to mkdir() so that it does not raise a FileExistsError if the directory already exists.
exist_ok=TrueWhat if our directory requires parent directories to be made as well?
Similarly to the exist_ok flag, the parents flag will modify the default behavior, recursively creating directories as necessary.p.mkdir(exists_ok=True, parents=True)
If we want to bundle everything together into a tidy function we can do so as follows:def makeDirectory(path_to_directory):
p = Path(path_to_directory)
p.mkdir(exists_ok=True, parents=True)