Search code examples
pythondirectory-structuresubdirectory

How to find recursively empty directories in Python?


Similarly to GNU find's find . -type d -empty -delete I'd like to find empty directories including those with empty subdirectories (and subdirectories containing emtpy subdirs etc.), but without deleting them. Is there any existing solution or do I have to manually use os.walk (probably with topdown=False and keeping track of the empty subdirectories found so far)?


Solution

  • Ok, here's my manual solution using os.walk. The function is_empty can of course be modified, e.g. 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)