Skip to content

How to create nested directory in Python 3.5+?

Learn how to create nested directories in Python safely without errors.

We can make use of the pathlib library and its .mkdir() method to safely create a nested directory.

Import pathlib, use the Path object’s mkdir method. Pass the directory when Path object is created and exist_ok flag to the mkdir method.

import pathlib
pathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True) 

parents

if true, the missing parents of this path are created when needed.
if false, and if the parent doesn’t exist FileNotFoundError is raised.

exist_ok

If sent true, directory will be created again if it already exists. FileExistsError exceptions will be ignored but only if the last path component is not an existing non-directory file. If false, FileExistsError will be raised if the target directory already exists.

We can also pass the mode to determine file mode and access flags.

Path.mkdir(mode=0o777, parents=False, exist_ok=False)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.