How to create an encrypted ZIP file?

I am creating an ZIP file with ZipFile in Python 2.5, it works OK so far:

import zipfile, os

locfile = "test.txt"
loczip = os.path.splitext (locfile)[0] + ".zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()

But I couldn't find how to encrypt the files in the ZIP file. I could use system and call PKZIP -s, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution.


I created a simple library to create a password encrypted zip file in python. - here

import pyminizip

compression_level = 5 # 1-9
pyminizip.compress("src.txt", "dst.zip", "password", compression_level)

The library requires zlib.

I have checked that the file can be extracted in WINDOWS/MAC.


The duplicate question: Code to create a password encrypted zip file? has an answer that recommends using 7z instead of zip. My experience bears this out.

Copy/pasting the answer by @jfs here too, for completeness:

To create encrypted zip archive (named 'myarchive.zip') using open-source 7-Zip utility:

rc = subprocess.call(['7z', 'a', '-mem=AES256', '-pP4$$W0rd', '-y', 'myarchive.zip'] + 
                     ['first_file.txt', 'second.file'])

To install 7-Zip, type:

$ sudo apt-get install p7zip-full

To unzip by hand (to demonstrate compatibility with zip utility), type:

$ unzip myarchive.zip

And enter P4$$W0rd at the prompt.

Or the same in Python 2.6+:

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

pyminizip works great in creating a password protected zip file. For unziping ,it fails at some situations. Tested on python 3.7.3

Here, i used pyminizip for encrypting the file.

import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("src.txt",'src', "dst.zip", "password", compression_level)

For unzip, I used zip file module:

from zipfile import ZipFile

with ZipFile('/home/paulsteven/dst.zip') as zf:
    zf.extractall(pwd=b'password')