I am trying to remove the empty folders of a directory.
def remove_empty_dir(path):
try:
os.rmdir(path)
except OSError:
pass
def remove_empty_dirs(path):
for root, dirnames, filenames in os.walk(path):
for dirname in dirnames:
remove_empty_dir(os.path.realpath(os.path.join(root, dirname)))
remove_empty_dirs(path)
I have also tried with:
import shutil
shutil.rmtree(path)
But that removes everything, even those folders with contents. The problem is that I need to do it from inside to outside, this way if I have:
root_folder
child_folder1
grandchild_folder1.1 (empty)
child_folder2
granchild_folder2.1
granchild_folder2.2 (empty)
The program should delete grandchild_folder1.1, child_folder1 and child_folder2.2, but not the rest.