annotate content/Coding/023-finding-empty-dirs.rst @ 9:271bed1181df

New blog post on rebooting blog with Pelican.
author Brian Neal <bgneal@gmail.com>
date Sat, 01 Feb 2014 14:29:54 -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