Random Filename Generator

  • Share this:

Code introduction


This function generates a random filename that does not exist. It first defines the base name and extension of the file, then it loops to generate a random number, combines it with the base name and extension to form a filename, and checks if the file already exists. If it does, it continues the loop until it finds a filename that does not exist.


Technology Stack : Python built-in libraries

Code Type : Function

Code Difficulty : Intermediate


                
                    
import math
import os
import random
import re
import shutil
import sys

def generate_random_filename(directory, extension):
    base, ext = os.path.splitext(extension)
    while True:
        filename = f"{base}_{random.randint(1000, 9999)}{ext}"
        filepath = os.path.join(directory, filename)
        if not os.path.exists(filepath):
            break
    return filepath