List All Files, Folders And Subfolders Inside Each And Every Directory And Subdirectory In Python

List All Files, Folders And Subfolders Inside Each And Every Directory And Subdirectory In Python

Published on November 23 2022

In this tutorial you will see how to get list of all files, folders and subfolders from each directory and subdirectory using OS dot walk method in python. Also, will create dictionary having files and folder list in well-structured way.

Source Code

import os
folder_path = "H:\project-purpose"

# Method - 1 - Print All

for (current_folder, folders_in_current_folder, files_in_current_folder) in os.walk(folder_path):
     print('current folder - ' + str(current_folder))
     print('Folder Under Current Folder - ' + str(current_folder) + ' --> ' + str(folders_in_current_folder))
     print('Files Under Current Folder - ' + str(current_folder) + ' --> ' + str(files_in_current_folder))

# Method - 2 - Function call with structured dictionary output

def get_all_files_and_directories(input_path):
    data = {}
    for (current_folder, folders_in_current_folder, files_in_current_folder) in os.walk(input_path):
        data[current_folder] = {}
        data[current_folder]['folder-list'] = folders_in_current_folder
        data[current_folder]['file-list'] = files_in_current_folder

    return data

result = get_all_files_and_directories(folder_path)
print("Output --> " + str(result))
print("Output using preety print")
import pprint
pp = pprint.PrettyPrinter()
pp.pprint(result)


Next Tutorial