In this article we will discuss how to get list of all empty directories.
Python’s os module provides a function to iterate over a directory tree i.e.
os.walk(path)
It iterates of the directory tree at give path and for each directory or sub directory it returns a tuple containing,
(<Dir Name> , <List of Sub Dirs> , <List of Files>.
Now let’s use this to create a list of empty directories in a directory tree.
Frequently Asked:
Creating a list of all empty Directories in a directory tree
- Create a list to Store empty directories
- Now Traverse all the files in given path using os.walk() :
- For each Directory, check if it has no files and sub directories. If yes then add its path in the list.
dirName = '/home/varun/temp'; ''' Get a list of empty directories in a directory tree ''' # Create a List listOfEmptyDirs = list() # Iterate over the directory tree and check if directory is empty. for (dirpath, dirnames, filenames) in os.walk(dirName): if len(dirnames) == 0 and len(filenames) == 0 : listOfEmptyDirs.append(dirpath)
Creating a list of all empty Directories in a directory tree using List Comprehension
More pythonic approach is a single line solution using List Comprehension,
listOfEmptyDirs = [dirpath for (dirpath, dirnames, filenames) in os.walk(dirName) if len(dirnames) == 0 and len(filenames) == 0]
Complete example is as follows,
import os def main(): dirName = '/home/varun/temp'; ''' Get a list of empty directories in a directory tree ''' # Create a List listOfEmptyDirs = list() # Iterate over the directory tree and check if directory is empty. for (dirpath, dirnames, filenames) in os.walk(dirName): if len(dirnames) == 0 and len(filenames) == 0 : listOfEmptyDirs.append(dirpath) # Iterate over the empty directories and print it for elem in listOfEmptyDirs: print(elem) print ("****************") listOfEmptyDirs = [dirpath for (dirpath, dirnames, filenames) in os.walk(dirName) if len(dirnames) == 0 and len(filenames) == 0] for elem in listOfEmptyDirs: print(elem) if __name__ == '__main__': main()
Output:
/home/varun/temp/temp1 /home/varun/temp/temp2 /home/varun/temp/temp3 **************** /home/varun/temp/temp1 /home/varun/temp/temp2 /home/varun/temp/temp3
Latest Python - Video Tutorial
Latest Video Tutorials