alphanumeric
alphanumeric

Reputation: 19329

How to compress files as password protected archive using Python

Is there a way to compress gzip or zipfile as a password protected archive? Here is an example code illustrating how to archive file with no password protection:

import gzip, shutil

filepath = r'c:\my.log'

with gzip.GzipFile(filepath + ".gz", "w") as gz:
    with open(filepath) as with_open_file:
        shutil.copyfileobj(with_open_file, gz)

import zipfile

zf = zipfile.ZipFile(filepath + '.zip', 'w')
zf.write(filepath)
zf.close()

Upvotes: 6

Views: 7543

Answers (2)

Mark Adler
Mark Adler

Reputation: 112304

Use gpg for encryption. That would be a separate wrapper around the archived and compressed data.

Upvotes: 1

L3viathan
L3viathan

Reputation: 27273

Python supports extracting password protected zips:

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

Sadly, it does not support creating them. You can either call an external tool like 7zip or use a third-party library like this zlib wrapper.

Upvotes: 4

Related Questions