Skip to content

Instantly share code, notes, and snippets.

@roddds
Last active September 20, 2021 12:36
Show Gist options
  • Save roddds/aff960f47d4d1dffba2235cc34cb45fb to your computer and use it in GitHub Desktop.
Save roddds/aff960f47d4d1dffba2235cc34cb45fb to your computer and use it in GitHub Desktop.
Recursively delete all empty directories
import os
for dirpath, dirnames, files in os.walk('.'):
if not (files or dirnames):
os.rmdir(dirpath)
@yvan-leroux-engineer
Copy link

This code was helpfull, however it's not recursive. To do so, I use a simple trick by counting the number of folder and subfolder, if it still the same the loop break and all empty folders are deleted :

`
ref_folder_counter = sum([len(folder) for r, folder, d in os.walk(source_path)])
post_folder_counter = 0

while ref_folder_counter != post_folder_counter :
ref_folder_counter = post_folder_counter
for dirpath, dirnames, files in os.walk(source_path):
if not (files or dirnames):
os.rmdir(dirpath)
`
Not the most elegant way to treat this question, but it works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment