Random String Generator in Directory

  • Share this:

Code introduction


This function creates a specified directory. If the directory does not exist, it is created, and then a file is generated in the directory with random string content.


Technology Stack : os, string, random

Code Type : File generator

Code Difficulty : Intermediate


                
                    
import os
import sys
import random
import string

def generate_random_string(length=10):
    letters = string.ascii_letters + string.digits
    return ''.join(random.choice(letters) for i in range(length))

def xxx(directory, filename):
    if not os.path.exists(directory):
        os.makedirs(directory)
    
    file_path = os.path.join(directory, filename)
    with open(file_path, 'w') as file:
        file.write(generate_random_string())                
              
Tags: