Python script: remove empty folders

One of the scripts I often use is this one to remove empty folders under a specific location on your hard drive. The usage is simple:

$ [path to the script]/remove_empty_folders.py [path_to_clean]

Here is the code:

#! /usr/bin/env python
import os, sys

def removeEmptyFolders(path):
  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:
    print "Removing empty folder:", path
    os.rmdir(path)

removeEmptyFolders(sys.argv[1])

Here is a sample output:

Removing empty folder: ./assorted/2010/12/13/20101213-202802
Removing empty folder: ./assorted/2010/12/13
Removing empty folder: ./assorted/2010/12/14/20101214-120800
Removing empty folder: ./assorted/2010/12/14
Removing empty folder: ./assorted/2010/12/01/20101201-070118
Removing empty folder: ./assorted/2010/12/01/20101201-070111
Removing empty folder: ./assorted/2010/12/01/20101201-070123
Removing empty folder: ./assorted/2010/12/01
Removing empty folder: ./assorted/2010/12

Please, use at your own risk. It should work on Windows also, but I have not tested it.

Enjoy!

Related Posts:

3 thoughts on “Python script: remove empty folders

  1. Per

    The second call on os.listdir can be avoided:


    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

  2. Greg

    I can confirm Windows functionality (tested on Windows 7). Worked like a charm, saved me some time figuring it out myself. Cheers mate!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType