python怎么批量压缩文件生成密码

30次阅读
没有评论

共计 1103 个字符,预计需要花费 3 分钟才能阅读完成。

要批量压缩文件并生成密码,可以使用 Python 的 zipfile 库和 random 库。
下面是一个示例代码,用于批量压缩指定文件夹中的所有文件,并生成随机密码:

import zipfile
import random
import string
import os
def generate_password(length):
"""生成随机密码"""
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(characters) for _ in range(length))
def compress_files(folder_path, output_path):
"""批量压缩文件并生成密码"""
with zipfile.ZipFile(output_path, 'w') as zipf:
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, os.path.relpath(file_path, folder_path))
password = generate_password(10)
with zipfile.ZipFile(output_path, 'a') as zipf:
zipf.setpassword(password.encode())
print(f"文件已压缩为 {output_path},生成的密码为 {password}")
# 示例用法
compress_files('/path/to/folder', '/path/to/output.zip')

这段代码首先定义了一个 generate_password 函数,用于生成指定长度的随机密码。然后定义了一个 compress_files 函数,用于批量压缩文件并生成密码。该函数接受两个参数,folder_path表示要压缩的文件夹路径,output_path表示压缩文件的输出路径。
compress_files 函数中,首先使用 zipfile.ZipFile 创建一个空的压缩文件。然后使用 os.walk 遍历文件夹中的所有文件,将它们写入到压缩文件中。接下来,使用 generate_password 函数生成随机密码,并使用 zipf.setpassword 为压缩文件设置密码。
最后,打印出生成的压缩文件路径和密码。
请注意,这只是一个示例代码,你可以根据实际需求进行修改和适配。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-22发表,共计1103字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)