Last active
September 20, 2021 12:36
-
-
Save roddds/aff960f47d4d1dffba2235cc34cb45fb to your computer and use it in GitHub Desktop.
Recursively delete all empty directories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
for dirpath, dirnames, files in os.walk('.'): | |
if not (files or dirnames): | |
os.rmdir(dirpath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.