SoFunction
Updated on 2025-03-03

Python tutorial on how to get all files in folders

Preface

Use Python to get all files in a folder, you can useosModule orpathlibModule.

1. Use the os module

1. Introduce modules:

#Introduce os moduleimport os

2. Method to obtain the specified folder (excluding subfolders):

# Subfolder not includeddef list_files_in_directory(directory):
    for filename in (directory):
        filepath = (directory, filename)
        # Check if it is a file (exclude directory)        if (filepath):
            print(filepath)

list_files_in_directory(r'C:\Users\admin\Desktop\Folder 1')

3. Method to obtain all files in a folder (subfolder):

# Subfolderdef list_files(path):
    for root, dirs, files in (path):
        level = (path, '').count()
        indent = ' ' * 4 * level
        print('{}{}/'.format(indent, (root)))
        redundant = ' ' * 4 * (level + 1)
        for f in files:
            print('{}{}'.format(redundant, f))

list_files(r'C:\Users\admin\Desktop\Folder 1')

2. Use the pathlib module

1. Introduce modules:

#Introduce pathlib modulefrom pathlib import Path

2. Method to obtain the specified folder (excluding subfolders):

# Subfolder not includeddef list_files_in_directory(directory):
    directory_path = Path(directory)
    for file in directory_path.iterdir():
        # Check if it is a file (exclude directory)        if file.is_file():
            print(file)


list_files_in_directory(r'C:\Users\admin\Desktop\Folder 1')

3. Method to obtain all files in a folder (subfolder):

# Subfolderdef list_files(path):
    p = Path(path)
    for file in ('*'):  # Use rglob('*') to recursively find all files        print(file)
        
# Calllist_files(r'C:\Users\admin\Desktop\Folder 1')

Summarize

This is the article about obtaining all files in Python folders. For more related Python folders, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!