简体   繁体   English

在 Python 中使用密码创建 ZipFile

[英]Create ZipFile with Password in Python

I have a folder Structure like this:我有一个这样的文件夹结构:

MainFolder
    |
   project.xml 
   SubFolder 1
      |
      Files
        |  
        wallpaper.png
        imp.docx
        pdf_1.pdf
    SubFolder 2
        |
        CategoryFolder
          |  
          Files
             |
             something.txt 

So the above is my folder structure.所以上面是我的文件夹结构。 I have to create a zipFile to the "MainFolder" with password and zipFile should contain all the files and folders as i have shown above.我必须使用密码为“MainFolder”创建一个 zipFile,并且 zipFile 应该包含我上面显示的所有文件和文件夹。 I was able to create zipFile without password but the requirement is zipFile with password.我能够在没有密码的情况下创建 zipFile,但要求是带有密码的 zipFile。 So how can i Achieve this.那我怎么能做到这一点。 pls help请帮忙

According to the documentation , the python zip library only uses password for extracting zip file (and not for creating them):根据文档,python zip 库仅使用密码来提取 zip 文件(而不是用于创建它们):

pwd is the password used to decrypt encrypted ZIP files. pwd 是用于解密加密的 ZIP 文件的密码。

There are some other packages that claim to allow that.还有一些其他软件包声称允许这样做。 Here's a piece of code that zips all the files in a folder named 'main':这是一段将所有文件压缩到名为“main”的文件夹中的代码:

from pathlib import Path
import pyminizip

# replace 'main' is your main folder. 
files = [f for f in Path("main").rglob("*") if f.is_file()]

paths = [str(f.parent) for f in files]
file_names = [str(f) for f in files]

# 123456 is the password. 3 is the compression level. 
pyminizip.compress_multiple(file_names, paths, "my.zip", "123456", 3)

The alternative solution would be to call the zip utility as a separate process using system , or preferably Popen .另一种解决方案是调用zip实用程序作为使用system的单独进程,或者最好是Popen

You can look in some packages as pyzipper.您可以将某些软件包视为 pyzipper。 According to documentation, this is根据文档,这是

Modification of Python's zipfile to read and write AES encrypted zip files.修改 Python 的 zipfile 以读写 AES 加密的 zip 文件。

Source资源

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

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