You can download this code by clicking the button below.
This code is now available for download.
This code generates a random string of specified length, then gets the current time, writes the string and time to a file. Then it calculates the MD5 hash of the string and saves the original string and hash to a JSON file.
Technology Stack : The packages and technologies used in the code[English]
Code Type : Function
Code Difficulty : Advanced
import random
import string
import time
import os
import sys
import hashlib
import json
def generate_random_string(length):
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
def xxx(arg1, arg2, arg3):
# 生成一个随机字符串
random_str = generate_random_string(10)
# 记录当前时间
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 将字符串和当前时间写入文件
with open('log.txt', 'a') as file:
file.write(f"{random_str}, {current_time}\n")
# 计算字符串的MD5散列值
md5_hash = hashlib.md5(random_str.encode()).hexdigest()
# 将MD5散列值和原始字符串保存到JSON文件
data = {
"original": random_str,
"hash": md5_hash
}
with open('data.json', 'w') as json_file:
json.dump(data, json_file)
# 确保写入文件
os.fsync(sys.stdout.fileno())
os.fsync(sys.stderr.fileno())