Wednesday, July 3, 2024
HomeLanguagesPythonHow to Delete Only Empty Folders in Python

How to Delete Only Empty Folders in Python

In this article, we are going to see how to delete only empty folders in Python.

Before deleting the folder, here is an image showing the files inside the main directory.

 

As the above image is showing that the folder has 2 empty sub-folders and 1 non-empty folder.

So, after running the code these 2 folders must get deleted.

By using os module

With the help of the module, we can easily get the files of any directory.

Python3




import os
  
for item in os.listdir(os.getcwd()):
    # print(item)
    # check dir
    if os.path.isdir(item):
        if os.listdir(item):
            print(os.path.join(os.getcwd(),item))
            os.removedirs(os.path.join(os.getcwd(),item))


Output:

 

By using loop

In this method, we will use the loop to find the content inside each folder. Then if the folder is empty, we will delete it.

Python3




import os
  
root = 'C:\\Users\\Untitled Folder\\'
folders = list(os.walk(root))[1:]
  
for folder in folders:
    print("All Folder -> ",folder)
    if not folder[2]:
        os.rmdir(folder[0])


Output:

All Folder ->  ('C:\\Users\\Untitled Folder\\.ipynb_checkpoints', [], ['Untitled-checkpoint.ipynb'])
All Folder ->  (C:\\Users\\Untitled Folder\\Empty Folder 1', [], [])
All Folder ->  ('C:\\Users\\Untitled Folder\\Empty Folder 2', [], [])
All Folder ->  ('C:\\Users\\Untitled Folder\\Non empty folder', [], ['untitled.txt'])

 

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments