Recursive File Listing Function

  • Share this:

Code introduction


This function recursively lists all files in a specified directory and its subdirectories.


Technology Stack : Pathlib, os.walk

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from pathlib import Path

def list_files_recursive(directory):
    """
    List all files in a directory and its subdirectories.
    """
    if not isinstance(directory, Path):
        directory = Path(directory)
    file_list = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = Path(root) / file
            file_list.append(file_path)
    return file_list