Random String Generator with File Output

  • Share this:

Code introduction


This function accepts two arguments, the first one is a string, and the second one is a non-negative integer. The function generates a random string with a length specified by the second argument and writes this string to a file named after the first argument, with a .txt extension.


Technology Stack : os, random, string, json

Code Type : File generation

Code Difficulty : Intermediate


                
                    
import os
import random
import string
import json

def generate_random_string(length=10):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def xxx(arg1, arg2):
    if not isinstance(arg1, str) or not isinstance(arg2, int):
        raise ValueError("arg1 must be a string and arg2 must be an integer")
    
    if arg2 < 0:
        raise ValueError("arg2 must be a non-negative integer")
    
    random_str = generate_random_string(arg2)
    filename = f"{arg1}_{random_str}.txt"
    with open(filename, 'w') as file:
        file.write(random_str)
    
    return filename