Open In App

How to Delete Only Empty Folders in Python

Last Updated : 04 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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'])

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads