You can download this code by clicking the button below.
This code is now available for download.
This function first creates a directory and then creates a file within it containing a random string. It then compresses the directory into a ZIP file and extracts it into another directory. Next, it calculates the hash value and modification time of the first file in the extracted file, and saves this information into a JSON file.
Technology Stack : os, string, random, zipfile, hashlib, datetime, json, re
Code Type : File management
Code Difficulty : Intermediate
import random
import string
import math
import os
import shutil
import zipfile
import json
import hashlib
import datetime
import re
def generate_random_string(length):
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
def xxx(arg1, arg2):
# 创建一个目录
os.makedirs(arg1, exist_ok=True)
# 创建一个包含随机字符串的文件
random_string = generate_random_string(10)
with open(os.path.join(arg1, random_string + '.txt'), 'w') as file:
file.write(random_string)
# 压缩目录
zip_path = os.path.join(arg1, 'archive.zip')
with zipfile.ZipFile(zip_path, 'w') as zipf:
zipf.write(arg1, arcname=os.path.basename(arg1))
# 读取压缩文件内容并解压到新目录
with zipfile.ZipFile(zip_path, 'r') as zipf:
zipf.extractall(arg2)
# 计算文件哈希值
hash_object = hashlib.sha256()
with open(os.path.join(arg2, os.listdir(arg2)[0]), 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_object.update(chunk)
file_hash = hash_object.hexdigest()
# 获取文件修改时间
mod_time = datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(arg2, os.listdir(arg2)[0]))).strftime('%Y-%m-%d %H:%M:%S')
# 创建JSON文件存储信息
with open(os.path.join(arg2, 'info.json'), 'w') as json_file:
json.dump({
'file_hash': file_hash,
'modified_time': mod_time
}, json_file)