Skip to content

Instantly share code, notes, and snippets.

@transacplus
Forked from kylexlau/del_empty_dirs.py
Last active November 1, 2020 10:28
Show Gist options
  • Save transacplus/4515172fca5b2090ffc704f4178153ad to your computer and use it in GitHub Desktop.
Save transacplus/4515172fca5b2090ffc704f4178153ad to your computer and use it in GitHub Desktop.
Python delete empty directories, recursive algorithm
import os
def del_empty_dirs(s_dir):
b_empty = True
for s_target in os.listdir(s_dir):
s_path = os.path.join(s_dir, s_target)
if os.path.isdir(s_path):
if not del_empty_dirs(s_path):
b_empty = False
else:
b_empty = False
if b_empty:
print('del: %s' % s_dir)
os.rmdir(s_dir)
return b_empty
def removeEmptyDir(path):
""" recurcive function to remove empty directories
version with scandir()
"""
obj = os.scandir(path)
toDelete = True
for entry in obj:
if entry.is_dir():
if not removeEmptyDir(path + '\\'+ entry.name):
toDelete = False
else :
toDelete = False
if toDelete:
print('delete :' + path + '\\' )
return toDelete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment