Random File Extension Selector

  • Share this:

Code introduction


This function randomly selects a file extension from all files in the specified directory. It raises an exception if the directory is empty or not a directory.


Technology Stack : Pathlib, Set

Code Type : Function

Code Difficulty : Intermediate


                
                    
from pathlib import Path
import random

def get_random_file_extension(directory):
    """
    Returns a random file extension from all files in the given directory.
    """
    if not isinstance(directory, Path):
        directory = Path(directory)
    
    if not directory.is_dir():
        raise ValueError("The provided path is not a directory.")
    
    files = list(directory.glob('*'))
    if not files:
        raise ValueError("The directory is empty.")
    
    file_extensions = {file.suffix for file in files}
    return random.choice(list(file_extensions))

# JSON Explanation                
              
Tags: