Python Example | Get All Files in Directory and Sub Directories

This python example code shows how to get all files in a directory and its sub directories.

import os

    For the given path, get the List of all files in the directory tree 
def getListOfFiles(dirName):
    # create a list of file and sub directories 
    # names in the given directory 
    listOfFile = os.listdir(dirName)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory 
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
    return allFiles
dirName = '/home/varun/Downloads';
# Get the list of all files in directory tree at given path
listOfFiles = getListOfFiles(dirName)

# Print the files
for elem in listOfFiles: