Random String Generator with Timestamped File Creation

  • Share this:

Code introduction


The function generates a random string and writes it to a text file named after the current time.


Technology Stack : datetime, random, string, os

Code Type : Function

Code Difficulty : Intermediate


                
                    
import math
import random
import string
import datetime
import os

def random_string(length=10):
    """
    Generate a random string of specified length.

    :param length: The length of the random string to generate.
    :return: A random string of the specified length.
    """
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def xxx(arg1, arg2):
    current_time = datetime.datetime.now()
    filename = f"{current_time.strftime('%Y%m%d%H%M%S')}_random.txt"
    with open(filename, 'w') as file:
        file.write(random_string(arg1) + '\n' + random_string(arg2))
    return filename