Random String Generator and File Operations

  • Share this:

Code introduction


The function xxx generates a random string, checks if a file exists, retrieves the current time, converts a dictionary to a JSON string, generates an MD5 hash, matches numbers with regular expressions, calculates an average, and clears all files in a directory.


Technology Stack : The function xxx uses the following Python built-in functions: generate_random_string, os.path.exists, datetime.datetime.now, json.dumps, hashlib.md5, re.compile, sum, map, int, len, and shutil.rmtree.

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import string
import os
import sys
import datetime
import json
import hashlib
import re
import math
import shutil

def generate_random_string(length, allowed_chars=string.ascii_letters + string.digits):
    return ''.join(random.choice(allowed_chars) for _ in range(length))

def xxx(arg1, arg2, arg3):
    # 创建一个随机字符串
    random_str = generate_random_string(10)
    
    # 检查文件是否存在
    if os.path.exists(arg1):
        print(f"File {arg1} exists.")
    else:
        print(f"File {arg1} does not exist.")
    
    # 获取当前时间
    current_time = datetime.datetime.now()
    
    # 将字典转换为JSON字符串
    data = {
        "name": arg2,
        "age": arg3
    }
    json_data = json.dumps(data)
    
    # 使用hashlib生成一个md5哈希值
    md5_hash = hashlib.md5(json_data.encode()).hexdigest()
    
    # 使用正则表达式匹配数字
    pattern = re.compile(r'\d+')
    numbers = pattern.findall(random_str)
    
    # 计算平均值
    average = sum(map(int, numbers)) / len(numbers) if numbers else 0
    
    # 清空一个目录下的所有文件
    if os.path.isdir(arg1):
        shutil.rmtree(arg1)
    else:
        print(f"Path {arg1} is not a directory.")