bgneal@4: Finding empty directories in Python bgneal@4: ################################### bgneal@4: bgneal@4: :date: 2013-05-26 16:00 bgneal@4: :tags: Python bgneal@4: :slug: finding-empty-directories-in-python bgneal@4: :author: Brian Neal bgneal@4: bgneal@4: Late one night I needed to write some Python code to recursively find empty bgneal@4: directories. Searching online produced some unsatisfactory solutions. Here is bgneal@4: a simple solution that leverages `os.walk`_. bgneal@4: bgneal@4: .. sourcecode:: python bgneal@4: bgneal@4: import os bgneal@4: bgneal@4: empty_dirs = [] bgneal@4: for root, dirs, files in os.walk(starting_path): bgneal@4: if not len(dirs) and not len(files): bgneal@4: empty_dirs.append(root) bgneal@4: bgneal@4: If you then wish to delete these empty directories: bgneal@4: bgneal@4: .. sourcecode:: python bgneal@4: bgneal@4: for path in empty_dirs: bgneal@4: os.removedirs(path) bgneal@4: bgneal@4: .. _os.walk: http://docs.python.org/2/library/os.html#os.walk