Create a Directory Using the OS Module
The most commonly used module of Python for creating a directory is the OS module. It has many built-in functions to do different types of file and directory-related operations. The main two functions of the OS module to create a permanent directory are mkdir() and makedirs(). The uses of these functions have been explained in this part of this tutorial.
Use of the os.mkdir() Function
The os.mkdir() function is used to create a directory with the permission bits. The function will raise FileExistsError error if the directory already exists in the system. The syntax of this function is given below.
Syntax:
- The first argument of this function is mandatory which defines the directory name with the path that will be created.
- The second argument of this function is optional which is used to set the permission of the directory for different users.
- The third argument, ‘*’ is used to define all following parameters and keyword-only parameters.
- The fourth argument is optional which is a file descriptor to refer to the directory.
- This function does not return anything.
Example-1: Create a Directory in the Current Location
Create a Python file named dir1.py with the following script to create a directory named MyDir in the current location by using the mkdir() function. The os.path.isdir() function will check if the MyDir directory already exist in the current location or not. If the directory does not exist, then os.mkdir() function will create the directory.
import os
#Initialize the directory name
dirname = "MyDir"
#Check the directory name exist or not
if os.path.isdir(dirname) == False:
#Create the directory
os.mkdir(dirname)
#Print success message
print("The directory is created.")
else:
#Print the message if the directory exists
print("The directory already exists.")
Run the following commands to check the current directory list. Execute the above Python script and again check the current directory list.
$ python3 dir1.py
$ ls
Output:
The following output shows that MyDir directory has been created after executing the above script.
Example-2: Create a Directory with Path and Permission
Create a Python file named dir2.py with the following script to create a directory named newDir under the directory, MyDir with the permission bits, 640 by using mkdir() function. The os.path.isdir() function will check if the MyDir/newDir path already exist in the current location or not. If the directory does not exist, then os.mkdir() function will create the directory.
import os
#Initialize the directory name with path
dirname = "MyDir/newDir"
#Check the directory name exist or not
if os.path.isdir(dirname) == False:
#Set the permission bits
permission = 0o640
#Create the directory
os.mkdir(dirname, permission)
#Print success message
print("The directory is created.")
else:
#Print the message if the directory exists
print("The directory already exists.")
Run the following commands to execute the above Python script and check the directory list with the permission of the directory, MyDir.
$ cd MyDir
$ ls -l
Output:
The following output shows that the newDir directory has been created after executing the above script with the permission, 0o640.
Use of the os.makedirs() Function
The os.makedirs() is another function of the OS module to create a directory recursively. This function can be used to create the directory and intermediate sub-directory also if the directory does not exist. The syntax of this function is given below.
Syntax:
- The first argument of this function is mandatory that is used to define the path of the directory
- The second argument of this function is optional which is used to set the permission of the directory for different users.
- The third argument is optional. If the target directory already exists then OSError will appear.
- This function does not return anything.
Example-3: Create a Directory with a Subdirectory
Create a Python file named dir3.py with the following script to create a directory named new_dir inside the path, temp/test by using the makedirs() function. The os.path.isdir() function will check if the new_dir directory already exist in the target path or not. If the directory does not exist, then os.makedirs() function will create the directory.
import os
#Initialize the directory name with path
dirname = "temp/test/new_dir"
#Check the directory name exist or not
if os.path.isdir(dirname) == False:
#Create the directory
os.makedirs(dirname)
#Print success message
print("The directory is created.")
else:
#Print the message if the directory exists
print("The directory already exists.")
Run the following commands to execute the above Python script and check the directory list.
$ cd temp/test
$ ls
Output:
The following output shows that the new_dir directory has been created after executing the above script.
Example-4: Create a Directory with Permission
Create a Python file named dir4.py with the following script to create a directory based on the directory name with the path taken from the user. The permission bit, 604 has been used in the second argument of the os.makedirs() function. If the directory does not exist, then os.makedirs() function will create the directory.
import os
#Initialize the directory name
dirname = input("Enter the directory name:")
#Check the directory name exist or not
if os.path.isdir(dirname) == False:
#Create directory with permission bits
os.makedirs(dirname, mode = 0o604)
#Print success message
print("%s directory has been created." % dirname)
else:
#Print the message if the directory exists
print("The directory already exists.")
Run the following commands to execute the above Python script and check the directory list.
$ ls
Output:
The following output will appear after executing the above script two times for the same directory name.
Creating a Temporary Directory
The TemporaryDirectory() function of tempfile module is used to create temporary directory. The temporary directory creates under the tmp directory, and the temporary directory removes after completing the execution of the program. Create a Python file named dir5.py with the following script to create a temporary directory.
Example-5: Create a Temporary Directory
import tempfile
#Create a temporary directory
with tempfile.TemporaryDirectory() as dirname:
print('Temporary directory %s has been created.' % dirname)
Run the following command to execute the above Python script.
Output:
The following output will appear after executing the above script.
Conclusion
The ways of creating permanent and temporary directories in Python have been shown in this tutorial by using the functions of OS and tempfile modules. I hope the Python users will be able to create any type of directory after reading this tutorial.