Sharath Nayak
Sharath Nayak

Reputation: 217

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. I was able to create zipFile without password but the requirement is zipFile with password. So how can i Achieve this. pls help

Upvotes: 0

Views: 2125

Answers (2)

Roy2012
Roy2012

Reputation: 12533

According to the documentation, the python zip library only uses password for extracting zip file (and not for creating them):

pwd is the password used to decrypt encrypted ZIP files.

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':

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.

Upvotes: 1

Dmitry
Dmitry

Reputation: 103

You can look in some packages as pyzipper. According to documentation, this is

Modification of Python’s zipfile to read and write AES encrypted zip files.

Source

Upvotes: 1

Related Questions