Files And Folder List In Python

Files And Folder List In Python

Published on November 23 2022

In this tutorial you will see how to get list of files and folder in Python using list directory method and also learn standard approach using function.

Source Code

import os
folder_path = 'H:\\project-purpose'
#folder_path = r'H:\project-purpose'

# Function
def get_files_and_dir_list(dir_path):
    file_list = []
    dir_list = []

    for result in os.listdir(dir_path):
        if os.path.isfile(os.path.join(dir_path, result)):
            file_list.append(str(result))
        if os.path.isdir(os.path.join(dir_path, result)):
            dir_list.append(str(result))

    return file_list, dir_list


# Calling function
file_list_output, dir_list_output = get_files_and_dir_list(folder_path)
print('File List:' + str(file_list_output))
print('Directory List:' + str(dir_list_output))