Random Filename Generator with Timestamp and Number

  • Share this:

Code introduction


This function generates a random file name with a specified extension, including a random timestamp and a random number, and saves it in the specified directory.


Technology Stack : datetime, re, sys, time, random, os

Code Type : Function

Code Difficulty : Intermediate


                
                    
import datetime
import re
import sys
import time
import random
import os

def generate_random_file_name(directory=".", extension=".txt"):
    """
    Generate a random file name with a given extension in a specified directory.

    :param directory: The directory in which to create the file. Defaults to the current directory.
    :param extension: The file extension. Defaults to '.txt'.
    :return: The full path of the generated file name.
    """
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    random_number = random.randint(1000, 9999)
    file_name = f"random_file_{timestamp}_{random_number}{extension}"
    full_path = os.path.join(directory, file_name)
    return full_path