Skip to content

Instantly share code, notes, and snippets.

@tantale
Last active August 26, 2016 08:48
Show Gist options
  • Save tantale/c2b2ded1b4b866338e41d8193b672ebc to your computer and use it in GitHub Desktop.
Save tantale/c2b2ded1b4b866338e41d8193b672ebc to your computer and use it in GitHub Desktop.
Reccursive rmdir with callback
# -*- coding: utf-8 -*-
import os
import stat
def prune_empty_dirs(root, callback=None, preserve=True):
"""
Prune empty directories in *root* directory, keeping it if *preserve* is ``True``.
Silently ignore errors.
The *callback* function is used to remove (or not) existing files, for instance temporary files.
The signature is ``callback(path, stat_info)``, where *path* is the full path of the file
and *stat_info* if the stat information given by :func:`os.stat` on this file.
For instance, one can get the last modification time to detect "old" files.
:type root: unicode
:param root: Root directory of the tree structure to prune.
:param callback: Callback used to remove files.
:type preserve: bool
:param preserve: Preserve the *root* folder is ``True`` even if empty.
"""
if callback is None:
# noinspection PyUnusedLocal
def callback(p, i):
pass
for path in (os.path.join(root, p) for p in os.listdir(root)):
stat_info = os.stat(path)
if stat.S_ISREG(stat_info.st_mode):
callback(path, stat_info)
elif stat.S_ISDIR(stat_info.st_mode):
prune_empty_dirs(path, callback, preserve=False)
if not preserve:
try:
os.rmdir(root)
except EnvironmentError:
pass
def process_file_and_remove(path, _):
# process the file
# ...
os.remove(path)
prune_empty_dirs("/path/to/root", process_file_and_remove)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment