How to find recursively empty directories in Python?

Like GNU, find find . -type d -empty -deleteI would like to find empty directories, including those with empty subdirectories (and subdirectories containing emtpy subtypes, etc.), but without deleting them . Is there an existing solution, or do I need to use it manually os.walk(maybe with topdown=Falseand track the empty subdirectories found so far)?

+4
source share
2 answers

Ok, here is my guide with help os.walk. The function is_emptycan, of course, be changed, for example. to exclude hidden files or in my example desktop.ini:

import os


def empty_dirs(root_dir='.', recursive=True):
    empty_dirs = []
    for root, dirs, files in os.walk(root_dir, topdown=False):
        #print root, dirs, files
        if recursive:
            all_subs_empty = True  # until proven otherwise
            for sub in dirs:
                full_sub = os.path.join(root, sub)
                if full_sub not in empty_dirs:
                    #print full_sub, "not empty"
                    all_subs_empty = False
                    break
        else:
            all_subs_empty = (len(dirs) == 0)
        if all_subs_empty and is_empty(files):
            empty_dirs.append(root)
            yield root


def is_empty(files):
    return (len(files) == 0 or files == ['desktop.ini'])


def find_empty_dirs(root_dir='.', recursive=True):
    return list(empty_dirs(root_dir, recursive))


print find_empty_dirs(recursive=False)
+2
source

os.walk:

import os

def find_empty_dirs(root_dir='.'):
    for dirpath, dirs, files in os.walk(root_dir):
        if not dirs and not files:
            yield dirpath

print list(find_empty_dirs())

, topdown=False , , - .

, , find . -type d -empty.

, , , find . -type d -empty -delete , , . os.walk , topdown=False.

, , :

import os

def recursive_delete_if_empty(path):
    """Recursively delete empty directories; return True
    if everything was deleted."""

    if not os.path.isdir(path):
        # If you also want to delete some files like desktop.ini, check
        # for that here, and return True if you delete them.
        return False

    # Note that the list comprehension here is necessary, a
    # generator expression would shortcut and we don't want that!
    if all([recursive_delete_if_empty(os.path.join(path, filename))
            for filename in os.listdir(path)]):
        # Either there was nothing here or it was all deleted
        os.rmdir(path)
        return True
    else:
        return False
+6

All Articles