having fun with code

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:

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

Here is the code:

  1. #! /usr/bin/env python
  2. import os, sys
  3.  
  4. def removeEmptyFolders(path):
  5.   if not os.path.isdir(path):
  6.     return
  7.  
  8.   # remove empty subfolders
  9.   files = os.listdir(path)
  10.   if len(files):
  11.     for f in files:
  12.       fullpath = os.path.join(path, f)
  13.       if os.path.isdir(fullpath):
  14.         removeEmptyFolders(fullpath)
  15.  
  16.   # if folder empty, delete it
  17.   files = os.listdir(path)
  18.   if len(files) == 0:
  19.     print "Removing empty folder:", path
  20.     os.rmdir(path)
  21.  
  22. removeEmptyFolders(sys.argv[1])

Here is a sample output:

  1. Removing empty folder: ./assorted/2010/12/13/20101213-202802
  2. Removing empty folder: ./assorted/2010/12/13
  3. Removing empty folder: ./assorted/2010/12/14/20101214-120800
  4. Removing empty folder: ./assorted/2010/12/14
  5. Removing empty folder: ./assorted/2010/12/01/20101201-070118
  6. Removing empty folder: ./assorted/2010/12/01/20101201-070111
  7. Removing empty folder: ./assorted/2010/12/01/20101201-070123
  8. Removing empty folder: ./assorted/2010/12/01
  9. 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:

1 Comment to Python script: remove empty folders

  1. Per's Gravatar Per
    August 25, 2011 at 10:47 | Permalink

    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

Leave a Reply

You can 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

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation