You can download this code by clicking the button below.
This code is now available for download.
This function generates a random filename with a specified extension.
Technology Stack : os, sys, random
Code Type : Function
Code Difficulty : Intermediate
import os
import sys
import random
def random_filename(ext="txt"):
"""Generate a random filename with a given extension.
Args:
ext (str, optional): The file extension. Defaults to "txt".
Returns:
str: A random filename.
"""
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
filename = "".join(random.choice(characters) for _ in range(10)) + "." + ext
return filename