How to create nested directories in Python
File creation and manipulation is considered a critical operation for any application. While creating a file, if any mistakes are made, it will affect the performance and working of the whole application. To create a nested directories from an absolute path is risky because the success of the command completely depends on the existing parent directories where nesting is done. Due care is required to be taken and monitored after directory creation.
The pathlib
library and the os
module have methods to safely create a nested directory. There are three different ways to create a nested directories.
- Using
pathlib.Path.mkdir()
- Using
os.makedirs()
- Using
distutils.dir_util
Method-1: Using pathlib.Path.mkdir()
The pathlib
module manipulates files and folders using the object-oriented approach. Firstly, we will need to import the Path class from the pathlib
module. Thereafter, create a new instance of Path class and initialize it with the nested directory structure to be created.
For all versions higher than or equal to 3.5, mkdir()
is used to create a new directory at a given path. The syntax of mkdir
is as shown below.
mkdir(mode=0o777, parents=False, exist_ok=False)
Here, all three parameters are optional. If mode is given, it determines the file mode and access flags. However, if the path already exists, then it will raise a FileExistsError
exception.
If the parameter parents is set to true, then any missing parents of this path are created with the default permissions without taking mode into account. However, if it is set to false, a missing parent will raise a FileNotFoundError exception.
If the parameter exist_ok
is true, FileExistsError
exceptions will be ignored but only if the last path component is not an existing non-directory file. Otherwise, it will raise a FileExistsError
exception.
Example 1:In this example, none of our parent directory is present. So, we will give parameter parents=True
so that directory hierarchy is created as we expect it to be.
# Importing Path from pathlib
from pathlib import Path
# Forming a directory structure required as a path
path = Path("C:/PythonDemo/NestedDemo")
# Using mkdir to create a directory structure and create the intermediate directories if they are not existing
path.mkdir(parents=True)
print("Directory structure created successfully")
Output
Directory structure created successfully
Example 2:In this example, we are demonstrating the use of exist_ok parameter.
# Importing Path from pathlib
from pathlib import Path
# Forming a directory structure required as a path
path = Path("C:/PythonDemo/NestedDemo/demoprograms")
# Using mkdir to create a directory structure and create the last path component if they are not existing
path.mkdir(exist_ok=True)
print("Directory structure created successfully")
Output
Directory structure created successfully
Method-2: Using os.makedirs()
In Python, os
module provides functions to interact with the operating system. It is provided under Python’s standard utility modules. Hence, this module provides an efficient way of using operating system dependent functionalities.
The makedirs()
method in Python is a recursive directory creation function like mkdir()
but also makes all intermediate directory to contain the leaf directory. If intermediate directories are not present then mkdir()
throws a FileNotFoundError exception. Whereas, makedirs
create all the intermediate directories. to create a directory named path with the given numeric mode. However, this method will raise a FileExistsError
exception if the directory to be created already exists.
If the parameter exist_ok
is true, FileExistsError
exceptions will be ignored but only if the last path component is not an existing non-directory file. Otherwise, it will raise a FileExistsError
exception.
The syntax of makedirs()
function is as shown below.
os.makedirs(name, mode, exist_ok=False)
Example 1:
# Importing os module
import os
# Forming a directory structure required as a path
path="C:/pydemo"
# Using makedirs to create a directory structure and create the last path component if they are not existing
os.makedirs(path, exist_ok=True)
print("Directory structure created successfully")
Output
Directory structure created successfully
Method-3: Using distutils.dir_util
The distutils.core
module is the only module that needs to be installed to use the Distutils
. The disutils.dir_util
module provides functions for operating on directories and trees of directories.
The mkpath()
function is used to create a directory and any missing parent directories. If the directory already exists then do nothing. However, if it is unable to create any directory structure on the way, it will raise DistutilsFileError
. The syntax of mkpath
is as shown below.
distutils.dir_util.mkpath(name,[mode, verbose=0])
If verbose is true, then it will print a one-line summary of each mkdir
to stdout
. This function will return the list of directories actually created.
Example 1: In this example, we are providing the absolute path of the directory as a name without any other arguments.
# Importing distuitils dir_util module
import distutils.dir_util
# Forming a directory structure required as a path and creating nested directory
# Using mkpath() function and printing
distutils.dir_util.mkpath("C:/PythonDemo/NestedDemo")
print("Directory structure created successfully")
Output
Directory structure created successfully
Example 2: In this example, we are providing the absolute path of the directory and verbose=1. Here, if there is an existing directory structure, it will return an empty list. However, if the given directory structure is created with the mkpath
then it will return the path of structure that has been created as a single entry in the list.
# Importing distuitils dir_util module
import distutils.dir_util
# Forming a directory structure required as a path and creating a nested directory
# Using mkpath() function and printing
distutils.dir_util.mkpath("C:/PythonDemo/NestedDemo", verbose=1)
print("Directory structure created successfully")
Output
Directory structure created successfully
C:/PythonDemo/NestedDemo']
Summary
The knowledge of creating nested directories is very important if we are performing any file operations in real time applications. While implementing any real time systems, many times we will need to store the result in the specific file structure whose naming is decided runtime, so we may need to create a nested directories structure to store that. In this tutorial, we covered the three different ways to create a nested directories with an example. All in all, this tutorial, covers everything that you need to know in order to create a nested directories in Python.
References
Pathlib Module
OS Module
distutils Module