Empty directories

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]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s