aut*_*ier 1 python zip python-3.x
使用 pyminizip 我可以在 python 中使用密码压缩文件:
filepath=r"C:\Users\xxx\Desktop\myFolder\file.txt"
import pyminizip
pyminizip.compress(filepath, None,"output.zip", "password", 0)
Run Code Online (Sandbox Code Playgroud)
但是如何将整个文件夹“myFolder”压缩到带有密码的 zip 文件中?我尝试从路径中删除文件名,但出现错误
OSError: error in opening C:\Users\xxx\Desktop\myFolder for reading
Run Code Online (Sandbox Code Playgroud)
编辑 :
下面的链接有一个可以压缩目录的功能。但它不会添加密码。
https://www.calazan.com/how-to-zip-an-entire-directory-with-python/
如果有人能让我知道是否可以向现有 zip 文件添加密码,这将解决我的问题。那可能吗?
我终于能够使用 Anupam Chaplot 建议的名为“pyzipper”的库来完成对整个目录(包括所有子文件夹结构和文件)的加密。
这是解决方案:
def zip_folderPyzipper(folder_path, output_path):
"""Zip the contents of an entire folder (with that folder included
in the archive). Empty subfolders will be included in the archive
as well.
"""
parent_folder = os.path.dirname(folder_path)
# Retrieve the paths of the folder contents.
contents = os.walk(folder_path)
try:
zip_file = pyzipper.AESZipFile('new_test.zip','w',compression=pyzipper.ZIP_DEFLATED,encryption=pyzipper.WZ_AES)
zip_file.pwd=b'PASSWORD'
for root, folders, files in contents:
# Include all subfolders, including empty ones.
for folder_name in folders:
absolute_path = os.path.join(root, folder_name)
relative_path = absolute_path.replace(parent_folder + '\\',
'')
print ("Adding '%s' to archive." % absolute_path)
zip_file.write(absolute_path, relative_path)
for file_name in files:
absolute_path = os.path.join(root, file_name)
relative_path = absolute_path.replace(parent_folder + '\\',
'')
print ("Adding '%s' to archive." % absolute_path)
zip_file.write(absolute_path, relative_path)
print ("'%s' created successfully." % output_path)
except IOError as message:
print (message)
sys.exit(1)
except OSError as message:
print(message)
sys.exit(1)
except zipfile.BadZipfile as message:
print (message)
sys.exit(1)
finally:
zip_file.close()
Run Code Online (Sandbox Code Playgroud)
由于我是 python 新手,我无法详细解释代码。以下是参考资料:
https://pypi.org/project/pyzipper/
https://www.calazan.com/how-to-zip-an-entire-directory-with-python/
要在 Windows 中解压生成的 ZIP 文件:
右键单击 - >解压缩(已加密)
如果直接点击Extract All选项,会报错