简体   繁体   English

如何使用Python将文件压缩为受密码保护的存档

[英]How to compress files as password protected archive using Python

Is there a way to compress gzip or zipfile as a password protected archive? 有没有办法将gzipzipfile压缩为受密码保护的存档? Here is an example code illustrating how to archive file with no password protection: 下面是一个示例代码,说明如何存档没有密码保护的文件:

import gzip, shutil

filepath = r'c:\my.log'

with gzip.GzipFile(filepath + ".gz", "w") as gz:
    with open(filepath) as with_open_file:
        shutil.copyfileobj(with_open_file, gz)

import zipfile

zf = zipfile.ZipFile(filepath + '.zip', 'w')
zf.write(filepath)
zf.close()

Python supports extracting password protected zips : Python支持提取受密码保护的zip

zipfile.ZipFile('myarchive.zip').extractall(pwd='P4$$W0rd')

Sadly, it does not support creating them. 可悲的是,它不支持创建它们。 You can either call an external tool like 7zip or use a third-party library like this zlib wrapper . 您可以调用外部工具(如7zip)或使用第三方库(如zlib包装器)

Use gpg for encryption . 使用gpg进行加密 That would be a separate wrapper around the archived and compressed data. 这将是存档和压缩数据的单独包装器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM