Random Filename Generator

  • Share this:

Code introduction


This function generates a random filename with a specified extension in a given directory.


Technology Stack : os, sys, datetime, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import sys
import datetime
import random

def get_random_filename(path=".", extension="txt"):
    """
    Generate a random filename with a given extension in the specified directory.
    """
    filename = f"random_{random.randint(1000, 9999)}{extension}"
    full_path = os.path.join(path, filename)
    return full_path