Today I got asked if it was possible to recurse through a folder structure and find all the empty directories within that structure. It sounded like a simple job for os.walk, and it was.
The os.walk recurses a directory structure returning a 3-tuple for each directory (including the starting directory) containing the directory path, a list of all the directories from that path and a list of all the files from that path. An empty directory has no folders and no files in it so this gives us an easy condition
import os for dirpath,dirs,files in os.walk(r'\\server\path\to\root\directory'): if (len(dirs)+len(files)) == 0: print(dirpath)
That lists all the empty directories to the screen but it would be more useful to have them in a list. Here the power of list comprehension comes into its own allowing us to do this with just one line of code
import os emptydirs = [dirpath for dirpath,dirs,files in os.walk(r'\\server\path\to\root\directory') if (len(dirs)+len(files)) == 0]