File manipulation is one of the most crucial skills to acquire in any programming language, and it must be done correctly. Errors may arise if the parent directory does not exist, or if other programs change files in the file system at the same time. Files allow you to store data outside of a program that can later be referenced by another application. When working with files, you may elect to establish a new directory in which to save a file.
Python Create Directory
Creating nested directories, especially from an absolute path, is risky because the command’s success is dependent on the parent directories being present to be nested within. There are numerous methods for creating a subfolder or nested directory. The procedures for creating a nested directory differ based on the version of Python you are running.
The most common methods to safely create Python Nested Directories are by using the Python pathlib library and the os library module. Before you can work with files in Python, we must compulsorily import these modules into our program.
For understanding how to safely create nested directories, we have considered 2 Directories – directoryA and directory, where directoryA is the parent directory to directoryB i.e. directoryB is nested in directoryA.
Example 1: Using pathlib.Path.mkdir
To build a nested directory in Python 3.5 and later, we use pathlib.Path.mkdir. We will first import Path from the pathlib module, build a Path object with the required path for our new file, then call the mkdir() method, which has the signature:
from pathlib import Path
p = Path('/root/directoryA/directoryB')
p.mkdir(parents = True, exist_ok = True)
Explanation
- We first import the Path class from the pathlib
- Then we create a Path object in which we include the directory paths to be created.
- Then we link the Path object to the .mkdir() method to create the directory.
- The parents parameter by default is set to False. We set the value to True. If the value is False, and if the parent directory is not found/present, then a FileNotFoundError is thrown. To avoid this we set the value to True.
- By default, exist_ok is False. If the directory already exists, the FileExistsError exception is thrown. To avoid this mistake, set it to True.
Note – We should always provide the entire path (absolute path) to the directory (not relative path). If the directory already exists, the above code will throw no error.
Example 2: Using os.makedirs
In Python, the OS module contains functions for interfacing with the operating system. This module provides a portable mechanism to access operating system-specific functions. In Python, the os.makedirs() method is used to construct a directory recursively. That is, if any intermediate-level directory is missing while creating a leaf directory, the os.makedirs() method will construct them all. You can use this method to create a folder inside an empty folder. The path to the folder you want to create is the only argument to os.mkdirs().
You can use the os.makedirs for Python versions 3.2 and above.
Example
import os
os.makedirs('/root/directoryA/directoryB')
- A nested directory can be easily constructed using the module os method makedirs().
- The nested directory we wished to construct was supplied as a parameter.
Example 3: Using distutils.dir_util
import distutils.dir_util
distutils.dir_util.mkpath('/root/directoryA/directoryB')
In this program, we have used the mkpath() method instead of mkdirs().
Example 4: Raising an exception if the directory already exists
import os
try:
   os.makedirs('/directoryA/directoryB')
except FileExistsError:
   print('File already exists')
This is a similar scenario to Example 2
- The statement is placed within the try
- If the directory already exists, the except block raises FileExistsError and executes the statements within the block.
Leave a Reply