You can download this code by clicking the button below.
This code is now available for download.
Create a directory, generate a random string, write the string to a file, and save the current time and the MD5 hash of the file to a JSON file.
Technology Stack : os, random, string, datetime, hashlib, json
Code Type : File manipulation and data processing
Code Difficulty : Intermediate
import os
import random
import string
import datetime
import hashlib
import json
import re
import sys
def generate_random_string(length=10):
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
def xxx(arg1, arg2):
# 创建一个目录
os.makedirs(arg1, exist_ok=True)
# 生成一个随机字符串
random_string = generate_random_string()
# 将字符串保存为文件
with open(os.path.join(arg1, random_string), 'w') as file:
file.write(arg2)
# 获取当前时间
current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 使用hashlib生成字符串的md5散列值
hash_object = hashlib.md5(arg2.encode())
hex_dig = hash_object.hexdigest()
# 将信息保存为JSON文件
info = {
'filename': random_string,
'content': arg2,
'date': current_time,
'hash': hex_dig
}
with open(os.path.join(arg1, 'info.json'), 'w') as json_file:
json.dump(info, json_file)