Jacob Tomlinson
Home Blog Talks Newsletter About

Python script: Recursively remove empty folders/directories

2 minute read #module, #python, #script

So as part of a script I’m writing I needed the ability to recursively remove empty folders/directories from a filesystem. After a bit of googling I found this very useful script by Eneko Alonso. However the script isn’t really in a usable state for what I want so I decided to make a few changes to it and publish it on GitHub.



# Remove empty folders under /path/to/clean including /path/to/clean
$ /path/to/script/remove_empty_folders.py /path/to/clean

# Remove empty folders under /path/to/clean not including /path/to/clean
$ /path/to/script/remove_empty_folders.py /path/to/clean False


#! /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):

  # 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):

  # if folder empty, delete it
  files = os.listdir(path)
  if len(files) == 0 and removeRoot:
    print "Removing empty folder:", 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"

  if not os.path.isdir(sys.argv[1]):
    print "No such directory %s" % sys.argv[1]

  if len(sys.argv) == 2 and sys.argv[2] != "False":
    print "removeRoot must be 'False' or not set"
    removeRoot = False

  removeEmptyFolders(sys.argv[1], removeRoot)

Have thoughts?

I love hearing feedback on my posts. You should head over to Twitter and let me know what you think!

Spotted a mistake? Why not suggest an edit!