Skip to content

Instantly share code, notes, and snippets.

@jacobtomlinson
Last active October 19, 2022 04:56
Show Gist options
  • Save jacobtomlinson/9031697 to your computer and use it in GitHub Desktop.
Save jacobtomlinson/9031697 to your computer and use it in GitHub Desktop.
Python Recursively Remove Empty Directories
#! /usr/bin/env python
'''
Module to remove empty folders recursively. Can be used as standalone script or be imported into existing script.
'''
import os, sys
def removeEmptyFolders(path, removeRoot=True):
'Function to remove empty folders'
if not os.path.isdir(path):
return
# remove empty subfolders
files = os.listdir(path)
if len(files):
for f in files:
fullpath = os.path.join(path, f)
if os.path.isdir(fullpath):
removeEmptyFolders(fullpath)
# if folder empty, delete it
files = os.listdir(path)
if len(files) == 0 and removeRoot:
print "Removing empty folder:", path
os.rmdir(path)
def usageString():
'Return usage string to be output in error cases'
return 'Usage: %s directory [removeRoot]' % sys.argv[0]
if __name__ == "__main__":
removeRoot = True
if len(sys.argv) < 1:
print "Not enough arguments"
sys.exit(usageString())
if not os.path.isdir(sys.argv[1]):
print "No such directory %s" % sys.argv[1]
sys.exit(usageString())
if len(sys.argv) == 2 and sys.argv[2] != "False":
print "removeRoot must be 'False' or not set"
sys.exit(usageString())
else:
removeRoot = False
removeEmptyFolders(sys.argv[1], removeRoot)
@clebiovieira
Copy link

Here, you found the folders... after that... use rmtree in a loop. :)

    empty_underlyings_path = [f.path
                              for f in os.scandir(self.__config.get_model_path())
                              if f.is_dir() and not os.listdir(f.path)]

@rnyren
Copy link

rnyren commented Apr 24, 2020

danke!

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