[Python] 纯文本查看 复制代码
import os
import random
import string
import subprocess
def compress_files_with_random_password(input_paths):
log_file = "compression_log.txt"
with open(log_file, 'a') as log:
for path in input_paths:
if os.path.exists(path):
# 生成随机密码
random_password = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
# 获取文件/文件夹的基本名
base_name = os.path.basename(path)
# 压缩文件/文件夹
compressed_file = f"{base_name}.zip"
subprocess.run(['zip', '-r', '-P', random_password, compressed_file, path])
# 记录压缩包名称、压缩包密码和参数列表到日志文件中
log.write(f"Compressed File: {compressed_file}, Password: {random_password}, Original Path: {path}\n")
else:
print(f"路径 '{path}' 不存在.")
# 测试脚本
input_paths = ["folder1", "file.txt", "folder2"]
compress_files_with_random_password(input_paths)
|