Register Login

Creating and Deleting Directories with Python

Updated Dec 06, 2021

Directories play a significant role in managing works and files in our computer system or even for handling large projects. File systems are not simply just to read and write files. There are a lot of useful things that can be done using directory and file system handling. One set of useful operations are creating and deleting a directory that helps in specifying similar files under one logical container name. In this article, you will learn how to create and delete directories from within your system through Python codes.

What is creating and deleting a directory?

Creating a directory is the process of making a folder in any specific or given path so that it can hold other directories and files within it. On the other hand, deleting a directory is the opposite, where the user will delete the file, and all other subdirectories and files created within it will also get deleted. To create or delete a directory in Python, you need to use the ‘os’ module within your program.

Detect the current working directory:

Detecting the current working directory is essential to understand how directories and subdirectories look like from within Python. The current working directory or present working directory is the directory in which a user works. The getcwd() method of the os module helps in fetching the current working directory using the program.

Program:

import os
path = os.getcwd()
print ("This is the current working directory in which I'm working: %s" % path)

Output:

This is the current working directory in which I'm working: D:\python

Explanation:

This is a simple program where we have imported the os module. Then, we have getcwd() method that will fetch the current working directory (absolute path) tracing the Python’s script and its directory where it is residing. We then store it in the path variable and use the print() function to display it. 

Creating a Directory using Python:

Method 1: Creating a directory is possible using Python's mkdir() method of the os module.

As a parameter, mkdir() will take the path-name for the directory where it will create the new folder.

Syntax:

os.mkdir(absolute_path, mode = mode-number, dir_fd = None)

Program:

import os
# defining a name that will act as directory
abspath = "D:/python/tempdr"
try:
    os.mkdir(abspath)
except OSError:
    print ("Creation of the directory %s failed" % abspath)
else:
    print ("Successfully created the directory %s" % abspath)

Output:

Successfully created the directory D:/python/tempdr

Explanation:

Here, we have to import the os modue. Then we define the path name that will act as directory for creating the new directory. Then within the try block, you have to create the directory as per the path string created and stored in the “abspath” object as parameter within the mkdir() method of os module. But if the path is already there, the directory creation won’t work and will generate an exception. This exception will be handled by the OSError and will print that it failed using the print() function. Otherwise, it will print “Successfully created the directory” through the print() function.

Method 2: Create Multiple Directories and Sub-Directories

There is another method to create multiple directories simultaneously. It is using the help of makedirs() method. It can create multi-level subdirectories by creating one directory after the next.

Syntax:

os.makedirs(absolute_path, mode_of_using)

Program:

import os
dirc = "Karlos"
parent_path = "D:/python"
abspath = os.path.join(parent_path, dirc)
os.makedirs(abspath)
print("Creating directory '% s' Now" % dirc)
dirc = "Programming"
parent_path = "D:/python/bg"
mode = 0o666
abspath = os.path.join(parent_path, dirc)
os.makedirs(abspath, mode)
print("Directory '% s' created together" % dirc)

Output:

Creating directory 'Karlos' Now
Directory 'Programming' created together

Explanation:

Another method to create multiple directories is also possible. In this program first we have to import the os module. Then we create a string (the directory that we want to create) and store it dirc variable. Then we create an absolute path "D:/Pycha" from where this program will check whether the ‘dirc’ string named folder exists or not. If yes, it will create that from this directory path. We join the complete path along with the string using the os.path.join() method and store it in the abspath object. os.makedirs() and passed the abspath as its parameter to create that directory.

We then print the message of directory creation using the print() function. We are doing the same thing again for another directory creation. Here we are creating the directory with the mode value. A mode value is an integer value that represents how the directory needs to be created.
If this parameter is not given, then default, its value becomes Oo777. We then print the successful creation of another directory. So both directories are created simultaneously. If a directory already exist in their given path, then the program will create an error in this case.

Deleting a Directory:

Method  1: Deleting a directory

is just the reverse or counter case of creating a directory. Programmers can create it using the rmdir() method of the os module. The rmdir() requires the absolute path string that comprises the directory name, and only deletes the deepest entry from within the path string. It is to be noted that the rmdir() works only when the directory is completely empty. If it is not empty, it will pop up with an OSError.

Program:

import os
# defining a name of the directory
abspath = "D:/python/Karlos"
try:
    os.rmdir(abspath)
except OSError:
    print ("Deletion of the directory %s failed" % abspath)
else:
    print ("Successfully deleted the directory %s" % abspath)

Output:

Successfully deleted the directory D:/python/Karlos

Explanation:

In this program first we have to import the os module. Then we create a string (the directory that we want to create) and store it abspath variable. Then within the try block, you have to delete the directory as per the path string given and stored in the “abspath” object as parameter within the rmdir() method of os module. But if the path does not exist there, the directory deletion won’t work and will generate an exception.

This exception will be handled by the OSError and will print that it failed using the print() function. Otherwise, it will print “Successfully deleted the directory” through the print() function.

Method 2: Delete the folder if empty:

This is another technique that leverages the same rmdir() method of the os module. But here the deletion will takes place only if the folder is not having any subfolders or files. This is checked using the Path() with iterdir() module.

Program:

import os
from pathlib import Path
abspath = "D:/Pycha/Karlos"
try:
    is_empty = not any(Path('D:/Pycha/Karlos').iterdir())
    if(is_empty==False):
        print("Warning: THE DIRECTORY YOU WANT TO DELETE CONTAINS FILES or OTHER SUB-DIRECTORS....")
    else:
        os.rmdir(abspath)
except OSError:
    print ("Deleting the directory %s failed" % abspath)
else:
    if (is_empty == False):
        pass
    else:
        print ("Deleted the specifed directory %s successfully" % abspath)

Output:

Deleting the directory D:/Pycha/Karlos failed

Explanation:

In this program first we have to import the os module. We will also import pathlib from Path. Then we create a string (the directory that we want to create) and store it abspath variable. Then within the try block, we will check whether the path whether the path and the directory that we want to delete is having any subdirectory or empty using the iterdir() aznd store it in a variable is_empty.

Then we will use the if condition to check is_empty==False, we will display a message showing that the directory is not empty and has either sub-directories or files. Otherwise, in the else part it will perform the os.rmdir() and remove the path given in the abspath. In case the path does not exist there, the directory deletion won’t work and will generate an exception.

This exception will be handled by the OSError and will print that it failed using the print() function. Otherwise, it will print “Successfully deleted the directory” through the print() function.

Method 3: Deleting Directory Recursively:

This is another method of deleting all the sub-directories along with the main directory (of the mentioned path). This recursively deletes all the sub directories one by one residing within the parent directory mentioned in the path. The function calls itself in for deleteing each directory and sub-directory.

Program:

from pathlib import Path
def rmdir(dirc):
    dirc = Path(dirc)
    for itm in dirc.iterdir():
        if itm.is_dir():
            rmdir(itm)
            print("Deleting", itm, ".... successful.")
        else:
            itm.unlink()
    dirc.rmdir()

rmdir(Path("D:/Pycha"))
print("Deleting main Directory .... Successful.")

Output:

Explanation:

First, we will import the Path from the pathlib module. Next, we will create a user-defined function rmdir() and pass a value that will store the directory path whose sub-directories and the directory itself need to be deleted.

We will prepare this as our path on which all other operations will be performed. We will then loop through all the subdirectories using the dirc.iterdir() and store it in the itm. The for loop will iterate until all the sub-directores gets deleted and the becomes empty. Within the for loop, the if condition checks whether itm.is_dir() exists or not.

If the directory exists, it will delete it successfully. Otherwise it will unlink the item using the itm.unlink() method. The user-defined function will keep calling itself until the main directory gets deleted. Lastly we called this recursive function and use the print() function to display the final message.

Conclusion:

Both creation and deletion are essentially used while creating large projects that require data storage in categories or multiple directories and subdirectories. It is essential to keep in mind the number of parameters this method uses to create or delete any directory.

The path parameter is compulsory. Rest, all other parameters are optional. This technique is also used to create virus and antivirus programs. Even cyber criminals use this technique to target specific folders to delete or attack.


×