How can I safely create a nested directory | Python

The pathlib library and its .mkdir() method offer a technique to safely create a nested directory. If you are using Python 3.5 or above, use pathlib.Path.mkdir:
from pathlib import Path Path("/myDir/nested").mkdir(parents=True, exist_ok=True) print("done")
pathlib.Path.mkdir as used above recursively creates the directory and does not raise an exception if the directory already exists. If you don't need or want the parents to be created, skip the parents argument.


In order to create the directory without causing exceptions and errors add the exist_ok flag to mkdir() so that it does not raise a FileExistsError if the directory already exists. If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists. If using Python 3.4 , even though it comes with pathlib, it is missing the useful exist_ok option.


If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command). If parents is false (the default), a missing parent raises FileNotFoundError.

TypeError: mkdir() got an unexpected keyword argument 'exists_ok'

from pathlib import Path p = Path("/MyDir/directory") p.mkdir(exists_ok=True, parents=True)
In some cases, if you are using older versions of Python, you will get the following exception.
Python Program to Safely Create a Nested Directory
If you are using the latest versions of Python , change the line like the following:
Path("/myDir/nested").mkdir(parents=True, exist_ok=True)