You can download this code by clicking the button below.
This code is now available for download.
This function accepts a directory path and a file extension as arguments, and returns a randomly selected file with the specified extension from the given directory path.
Technology Stack : Pathlib
Code Type : Function
Code Difficulty : Intermediate
import random
from pathlib import Path
def find_random_file_in_directory(directory_path, file_extension):
"""
随机选择一个指定扩展名的文件,该文件位于给定的目录路径下。
"""
if not isinstance(directory_path, Path):
directory_path = Path(directory_path)
if not directory_path.is_dir():
raise ValueError("提供的路径不是一个有效的目录")
files = [f for f in directory_path.iterdir() if f.is_file() and f.suffix == file_extension]
if not files:
raise FileNotFoundError(f"No files with extension {file_extension} found in {directory_path}")
return random.choice(files)