Mercurial > public > pelican-blog
diff content/Coding/023-finding-empty-dirs.rst @ 4:7ce6393e6d30
Adding converted blog posts from old blog.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Thu, 30 Jan 2014 21:45:03 -0600 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/content/Coding/023-finding-empty-dirs.rst Thu Jan 30 21:45:03 2014 -0600 @@ -0,0 +1,29 @@ +Finding empty directories in Python +################################### + +:date: 2013-05-26 16:00 +:tags: Python +:slug: finding-empty-directories-in-python +:author: Brian Neal + +Late one night I needed to write some Python code to recursively find empty +directories. Searching online produced some unsatisfactory solutions. Here is +a simple solution that leverages `os.walk`_. + +.. sourcecode:: python + + import os + + empty_dirs = [] + for root, dirs, files in os.walk(starting_path): + if not len(dirs) and not len(files): + empty_dirs.append(root) + +If you then wish to delete these empty directories: + +.. sourcecode:: python + + for path in empty_dirs: + os.removedirs(path) + +.. _os.walk: http://docs.python.org/2/library/os.html#os.walk