Skip to content

Python zip file with password

  • by

Use the pyminizip module to create a zip file with a password in Python. The pyminizip module can be installed using the below command:

pip install pyminizip

Syntax

pyminizip.compress("/srcfile/path.txt", "file_path_prefix", "/distfile/path.zip", "password", int(compress_level))

Read: https://github.com/smihica/pyminizip

Python zip file with password

Simple example code.

# importing module
import pyminizip

# input file path
inpt = "./Text.txt"

# prefix path
pre = None

# output zip file path
oupt = "./output.zip"

# set password value
password = "GFG"

# compress level
com_lvl = 5

# compressing file
pyminizip.compress(inpt, None, oupt, password, com_lvl)

Output:

Python zip file with password

Extracting a Zip with Password

To extract a Zip with a password, you need to pass a value to pwd positional argument of extract(pwd = password) or extractall(pwd = password) methods.

## extracting zip with password
import zipfile

def main():
    file_name = 'pswd_file.zip'
    pswd = 'password'

    with zipfile.ZipFile(file_name) as file:
        # password you pass must be in the bytes you converted 'str' into 'bytes'
        file.extractall(pwd = bytes(pswd, 'utf-8'))

if __name__ == '__main__': main()

How to set a password for a Zipfile?

Answer: The password should be bytes, not str.

zf.setpassword(b"1234")

Do comment if you have any doubts or suggestions on this Python Zipfile topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading