You can download this code by clicking the button below.
This code is now available for download.
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