Mercurial > public > pelican-blog
annotate content/Coding/023-finding-empty-dirs.rst @ 10:6c03ca07a16d
Renamed my tools directory to "tools".
I named it __bgn because I was worried it would clash with a future Pelican
updaet. But it seems like this would only happen if I re-ran the quickstart
script. "tools" is a better name. :)
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Sun, 02 Feb 2014 11:32:13 -0600 |
parents | 7ce6393e6d30 |
children |
rev | line source |
---|---|
bgneal@4 | 1 Finding empty directories in Python |
bgneal@4 | 2 ################################### |
bgneal@4 | 3 |
bgneal@4 | 4 :date: 2013-05-26 16:00 |
bgneal@4 | 5 :tags: Python |
bgneal@4 | 6 :slug: finding-empty-directories-in-python |
bgneal@4 | 7 :author: Brian Neal |
bgneal@4 | 8 |
bgneal@4 | 9 Late one night I needed to write some Python code to recursively find empty |
bgneal@4 | 10 directories. Searching online produced some unsatisfactory solutions. Here is |
bgneal@4 | 11 a simple solution that leverages `os.walk`_. |
bgneal@4 | 12 |
bgneal@4 | 13 .. sourcecode:: python |
bgneal@4 | 14 |
bgneal@4 | 15 import os |
bgneal@4 | 16 |
bgneal@4 | 17 empty_dirs = [] |
bgneal@4 | 18 for root, dirs, files in os.walk(starting_path): |
bgneal@4 | 19 if not len(dirs) and not len(files): |
bgneal@4 | 20 empty_dirs.append(root) |
bgneal@4 | 21 |
bgneal@4 | 22 If you then wish to delete these empty directories: |
bgneal@4 | 23 |
bgneal@4 | 24 .. sourcecode:: python |
bgneal@4 | 25 |
bgneal@4 | 26 for path in empty_dirs: |
bgneal@4 | 27 os.removedirs(path) |
bgneal@4 | 28 |
bgneal@4 | 29 .. _os.walk: http://docs.python.org/2/library/os.html#os.walk |