How to delete only empty folders in Python
Hello folks, in this tutorial we are going to discuss how to delete only empty folders in Python. This is very useful because we can delete multiple empty folders at a time.
Delete only empty folders in Python using os and shutil libraries
Let’s consider a folder “sample” which consists of two empty folders and one folder which consists of a .txt file.
The file structure is given below:
sample folder consists of three folders named “Empty1”, “Empty2”, “NotEmpty”. NotEmpty consists of a text file.
—>NotEmpty -(folder) —> random.txt-(text file)
Since our goal is to delete empty folders in a given folder, our code should delete “Empty1” and “Empty2” and leave the “NotEmpty” folder since it contains a text file.
Functions/methods used in the code:
This method traverses the given file and for each directory, it returns a tuple.
The tuple consists of three elements:
- Path of the file/directory
- All files in the directory
This method returns all the files and directories present in the specified location
Learn more about the os module here.
This method helps in deleting the directory given in the path.
Let’s look into the code
import os import shutil def delete_empty_folders(folder_location): all_directories = list(os.walk(folder_location)) for path, a, b in all_directories: if len(os.listdir(path)) == 0: #Checking if the directory is empty or not shutil.rmtree(path) #Delete the folder if it is empty if __name__ == '__main__': delete_empty_folders("C:/Users/niks/Desktop/sample") #This path is just an example
After executing the above code, the empty folders "Empty1" and "Empty2" are deleted. The "NonEmpty" folder isn't deleted since it contains a text file
Leave a Reply