Thursday, February 5, 2026
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

1 COMMENT

Most Popular

Dominic
32489 POSTS0 COMMENTS
Milvus
126 POSTS0 COMMENTS
Nango Kala
6861 POSTS0 COMMENTS
Nicole Veronica
11983 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12071 POSTS0 COMMENTS
Shaida Kate Naidoo
6994 POSTS0 COMMENTS
Ted Musemwa
7234 POSTS0 COMMENTS
Thapelo Manthata
6946 POSTS0 COMMENTS
Umr Jansen
6929 POSTS0 COMMENTS