Skip to content

Instantly share code, notes, and snippets.

@jacobtomlinson
Last active December 22, 2025 16:23
Show Gist options
  • Select an option

  • Save jacobtomlinson/9031697 to your computer and use it in GitHub Desktop.

Select an option

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)
@alexwhb

alexwhb commented Jul 28, 2016

Copy link
Copy Markdown

you saved me a bunch of time with this. Thank you. 👍

@MaynardTool

Copy link
Copy Markdown

Nice one. Thanks very much!

@macosas

macosas commented Apr 20, 2017

Copy link
Copy Markdown

Thank you very much, work so fine.

@elecs7g

elecs7g commented May 24, 2017

Copy link
Copy Markdown

How about this code.
def removeEmptyfolders(path):
for (_path, _dirs, _files) in os.walk(path, topdown=False):
if _files: continue # skip remove
try:
os.rmdir(_path)
print('Remove :', _path)
except OSError as ex:
print('Error :', ex)

@velcroMustacho

Copy link
Copy Markdown

Sorry, I'm a total newby to Python-
Do i just stick this script in the associated folder and run it from in there? Or do i specify the directory somewhere in the code?
Thanks!

@dstromberg

Copy link
Copy Markdown

@velcroMustacho:

For jacobtomlinson's, put the script in a different directory, and pass the root of the directory hierarchy you want to clean on the command line. It's shell-callable.

elecs7g's is Python-callable - put it inside your script (other than jacobtomlinson's :), and pass it the root of the directory hierarchy you want to clean as a python string (str).

@tanujkapoor15

Copy link
Copy Markdown

what is removeRoot used for?

@yonglam

yonglam commented Nov 23, 2018

Copy link
Copy Markdown

what is removeRoot used for?

It ought to been removed, I guess.

@roddds

roddds commented Apr 28, 2019

Copy link
Copy Markdown

This accomplishes basically the same thing with 6 lines: https://gist.github.com/roddds/aff960f47d4d1dffba2235cc34cb45fb

@DarthThomas

Copy link
Copy Markdown

This accomplishes basically the same thing with 6 lines: https://gist.github.com/roddds/aff960f47d4d1dffba2235cc34cb45fb

I think the one with 6 lines is not Recursively deleting the empty folders. if you have:

.
├── 43
│   └── 2019-06-17
│       ├── 0
│       └── 1
├── 44
│   └── 2019-06-17
│       ├── 0
│       ├── 1
│       ├── 2
│       └── 3
├── 45
│   └── 2019-06-17
│       ├── 0
│       ├── 1
│       └── 2
└── 46
    └── 2019-06-17
        └── 0

such that all folders with len(name) == 1 are empty. This code would delete them all but the 6-line version only deletes ones with len(name) == 1

@SzieberthAdam

SzieberthAdam commented Jan 8, 2020

Copy link
Copy Markdown

Pass a pathlib.Path instance to the function below:

def remove_empty_directories(pathlib_root_dir):
  # list all directories recursively and sort them by path,
  # longest first
  L = sorted(
      pathlib_root_dir.glob("**"),
      key=lambda p: len(str(p)),
      reverse=True,
  )
  for pdir in L:
    try:
      pdir.rmdir()  # remove directory if empty
    except OSError:
      continue  # catch and continue if non-empty

@clebiovieira

Copy link
Copy Markdown

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

rnyren commented Apr 24, 2020

Copy link
Copy Markdown

danke!

@pagebase

Copy link
Copy Markdown
import os

def remove_empty_folders(root_path):
    # Walk through the directory tree in reverse order (bottom-up)
    for dirpath, dirnames, filenames in os.walk(root_path, topdown=False):
        # Check if the directory is empty (no files and no subdirectories)
        if not dirnames and not filenames:
            try:
                os.rmdir(dirpath)
                print(f"Removed empty directory: {dirpath}")
            except OSError as e:
                print(f"Could not remove {dirpath}: {e}")

# Specify the root path (C drive)
root_path = "C:\\"

# Call the function to remove empty folders
remove_empty_folders(root_path)   

This code also work fine, but can't remove system's empty directories. Is there any robust way to delete empty system directories?

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