'Create a password protected zip file in-memory and write to disk

from io import BytesIO
import zipfile

mem_zip = BytesIO()

with zipfile.ZipFile(mem_zip, mode="w",compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr("filename.txt", b"test")

data = mem_zip.getvalue()

with open('/path/to/file/test.zip', 'wb') as f:
    f.write(data)

The code sinppet above creates a zip file in-memory with and writes to disk as a zip file. This works as expected. I can extract it and see the text file with the content "test".

I wish to password protect my zipfile. How do I do that?

I tried using the setpassword method but that had no effect on the output. The file written to disk was not password protected.

with zipfile.ZipFile(mem_zip, mode="w",compression=zipfile.ZIP_DEFLATED) as zf:
        zf.setpassword(b"test_password")
        zf.writestr("filename.txt", b"test")

I am writing to disk here just to test if the zipfile looks as I expect. My goal is to send the file as an email attachment and I wish to keep the zip file in-memory. So using pyminizip is not an option for me.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source