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