赞
踩
以下是压缩代码(使用随机密码功能时会在指定的文件夹生成一个随机加密密码的word文档):
import os
import py7zr
import random
import docx
input_folder = input("请输入要压缩的文件夹地址:")
output_folder = input("请输入指定(放置压缩文件)文件夹地址:")
encrypt = input("是否加密?请输入是或否:")
if encrypt == "是":
random_encrypt = input("是否随机加密?请输入是或否:")
if random_encrypt == "否":
password = input("请输入密码:")
else:
password = None
count = 0
if encrypt == "是":
document = docx.Document()
for item in os.listdir(input_folder):
item_path = os.path.join(input_folder, item)
item_name = os.path.basename(item_path)
if os.path.commonpath([item_path, input_folder]) == input_folder:
if encrypt == "是" and random_encrypt == "是":
password = str(random.randint(1000, 9999))
print(f"{item_name}的随机密码是:{password}")
document.add_paragraph(f"{item_name}的随机密码是:{password}")
archive = py7zr.SevenZipFile(os.path.join(output_folder, item_name + ".7z"), mode="w", password=password)
if os.path.isfile(item_path):
archive.write(item_path, arcname=item_name)
elif os.path.isdir(item_path):
archive.writeall(item_path, arcname=item_name)
archive.close()
count += 1
print(f"压缩完毕,共压缩了{count}个文件。")
if encrypt == "是":
document.save(os.path.join(output_folder, "加密密码.docx"))
以下是对应的批量解上一个代码随机密码的python代码,注意,含有加密密码的文档和需要解压的文件不要放同一个文件夹下,否则无法使用,最好是将加密密码的文档移到新的文件夹,有使用问题可以问我,对代码的修改问题不要问我:
import os
import py7zr
import docx
decompress = input("是否解压?请输入是或否:")
if decompress == "是":
decompress_folder = input("请输入要解压的文件夹地址:")
output_folder = input("请输入指定文件夹地址(放置解压文件):")
password_folder = input("请输入有加密密码word文档的文件夹地址:")
count = 0
password_dict = {}
document = docx.Document(os.path.join(password_folder, "加密密码.docx"))
for paragraph in document.paragraphs:
text = paragraph.text
if "随机密码" in text:
file_name = text.split("的随")[0]
password = text[-4:]
password_dict[file_name] = password
for item in os.listdir(decompress_folder):
item_path = os.path.join(decompress_folder, item)
item_name = os.path.basename(item_path)
if item_name.endswith(".7z"):
password = password_dict.get(item_name[:-3], None)
if password is not None:
archive = py7zr.SevenZipFile(item_path, mode="r", password=password)
archive.extractall(output_folder)
archive.close()
count += 1
print(f"解压完毕,共解压了{count}个文件。")
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。