批量压缩文件夹内文件并记录解压密码

主要功能是:

遍历指定目录中的所有文件。
为每个文件生成一个随机密码。
使用生成的密码将文件压缩为 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.")

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用记事本编写的一个示例批处理脚本,用于批量压缩文件并为每个文件设置不同的密码: ``` @echo off setlocal enabledelayedexpansion set "zip_path=C:\Program Files\7-Zip\7z.exe" set "source_folder=C:\MyFiles" set "destination_folder=C:\CompressedFiles" set "passwords_file=C:\Passwords.txt" for %%F in ("%source_folder%\*.*") do ( set /p password=<"%passwords_file%" "%zip_path%" a -tzip -p!password! "%destination_folder%\%%~nF.zip" "%%F" ) echo All files zipped and password protected! ``` 在这个脚本中,你需要设置以下几个变量: - `zip_path`:7-Zip软件的安装路径。 - `source_folder`:待压缩文件所在的文件夹路径。 - `destination_folder`:压缩文件输出路径。 - `passwords_file`:包含密码的文本文件路径。每行一个密码,且密码的数量要与待压缩文件的数量相同。 脚本中的`for`循环遍历每个文件,从密码文件中读取对应的密码,然后使用7-Zip软件将文件压缩为带密码保护的ZIP文件。 你可以使用记事本打开一个新的文本文件,在其中复制上面的示例脚本,然后修改变量的值以满足你的需求。当你完成修改后,可以按照以下步骤保存这个脚本: 1. 在菜单栏中选择“文件”->“另存为”。 2. 在“文件名”栏中输入一个合适的名称,如“compress.bat”。 3. 在“保存类型”中选择“All Files”。 4. 点击“保存”按钮,保存脚本文件到你的电脑上。 现在,你就可以双击这个脚本文件来运行它,实现批量压缩文件并为每个文件设置不同的密码了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑战士安全

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值