Random Selection from File List

  • Share this:

Code introduction


This function reads a list of items from a specified file and returns a random selection of items from that list.


Technology Stack : random

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
def random_select_list_from_file(file_path, num_items=5):
    """
    This function reads a list of items from a file and returns a random selection of items.
    """
    with open(file_path, 'r') as file:
        items = [line.strip() for line in file if line.strip()]
    return random.sample(items, min(num_items, len(items)))                
              
Tags: