You can download this code by clicking the button below.
This code is now available for download.
The function is used to generate a unique filename, consisting of a random number and a specified extension. If the generated filename already exists, it will keep generating new random numbers until a unique filename is found.
Technology Stack : os, random
Code Type : File operation
Code Difficulty : Intermediate
import os
import sys
import random
def generate_random_filename(directory, extension):
unique_filename = os.path.join(directory, f"{random.randint(1000, 9999)}{extension}")
while os.path.exists(unique_filename):
unique_filename = os.path.join(directory, f"{random.randint(1000, 9999)}{extension}")
return unique_filename