Mercurial > public > pelican-blog
comparison 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 |
comparison
equal
deleted
inserted
replaced
3:c3115da3ff73 | 4:7ce6393e6d30 |
---|---|
1 Finding empty directories in Python | |
2 ################################### | |
3 | |
4 :date: 2013-05-26 16:00 | |
5 :tags: Python | |
6 :slug: finding-empty-directories-in-python | |
7 :author: Brian Neal | |
8 | |
9 Late one night I needed to write some Python code to recursively find empty | |
10 directories. Searching online produced some unsatisfactory solutions. Here is | |
11 a simple solution that leverages `os.walk`_. | |
12 | |
13 .. sourcecode:: python | |
14 | |
15 import os | |
16 | |
17 empty_dirs = [] | |
18 for root, dirs, files in os.walk(starting_path): | |
19 if not len(dirs) and not len(files): | |
20 empty_dirs.append(root) | |
21 | |
22 If you then wish to delete these empty directories: | |
23 | |
24 .. sourcecode:: python | |
25 | |
26 for path in empty_dirs: | |
27 os.removedirs(path) | |
28 | |
29 .. _os.walk: http://docs.python.org/2/library/os.html#os.walk |