You can download this code by clicking the button below.
This code is now available for download.
This function lists all files with a specific extension in the given directory and all its subdirectories.
Technology Stack : Pathlib
Code Type : File search
Code Difficulty : Intermediate
import random
from pathlib import Path
def list_random_files(base_path, extension):
"""
List all files with a specific extension in a given base directory and its subdirectories.
:param base_path: The base directory where the search starts.
:param extension: The file extension to search for (without the dot).
:return: A list of Path objects for files with the specified extension.
"""
base_path = Path(base_path)
if not base_path.is_dir():
raise ValueError("The base_path must be a directory.")
return [file for file in base_path.rglob(f'*.{extension}')]