主要功能是:
遍历指定目录中的所有文件。
为每个文件生成一个随机密码。
使用生成的密码将文件压缩为 7z 格式。
将文件名和对应的密码记录到 passwords.txt 文件中。
import os
import random
import string
from py7zr import SevenZipFile, exceptions
# 设置文件夹路径
folder_path = r'D:\1'
password_file_path = os.path.join(folder_path, 'passwords.txt')
# 清除旧的密码文件
if os.path.exists(password_file_path):
os.remove(password_file_path)
print(f"Old password file '{password_file_path}' removed.")
# 生成一个安全的随机密码
def generate_password(length=10):
characters = string.ascii_letters + string.digits
return ''.join(random.choice(characters) for i in range(length))
# 遍历目录并压缩每个文件
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path):
password = generate_password()
archive_name = os.path.join(folder_path, f'{os.path.splitext(filename)[0]}.7z')
try:
# 创建压缩文件并设置密码
with SevenZipFile(archive_name, 'w', password=password) as archive:
archive.writeall(file_path, arcname=filename)
# 记录密码
with open(password_file_path, 'a') as f:
f.write(f'{filename}: {password}\n')
print(f"File '{filename}' compressed and password recorded.")
except exceptions.SevenZipError as e:
print(f"Error compressing file '{filename}': {e}")
else:
print(f"Skipping '{filename}', not a file.")
print("Compression and password recording completed.")