Random String Generator with File Creation

  • Share this:

Code introduction


Create a directory if it does not exist, generate a random string, and write the string to a file created in the directory.


Technology Stack : os, random, string

Code Type : File operation

Code Difficulty : Intermediate


                
                    
import datetime
import json
import os
import random
import re
import shutil
import string
import sys
import time

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

def xxx(arg1, arg2):
    # 创建一个目录
    if not os.path.exists(arg1):
        os.makedirs(arg1)
    
    # 生成一个随机字符串
    random_string = generate_random_string(12)
    
    # 将字符串写入文件
    with open(os.path.join(arg1, random_string + '.txt'), 'w') as file:
        file.write(arg2)
    
    # 返回生成的随机字符串
    return random_string                
              
Tags: