Friday, November 21, 2025
HomeLanguagesHow 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'])

 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6781 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11995 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7166 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS