Python Compression: Create Encrypted Archives in ZIP and 7z

Use Python to create encrypted compressed files in ZIP and 7z formats.

ZIP format compression

1
2
3
4
5
6
7
import pyzipper

with pyzipper.AESZipFile(dest + '.zip', "w", encryption=pyzipper.WZ_AES) as zf:
    zf.setpassword(b"password")
    for file in os.listdir(dest):
        fullfile = os.path.join(dest, file)
        zf.write(fullfile, file)
  • import pyzipper vs import zipfile
    pyzipper is mostly API-compatible with zipfile.
    zipfile can use passwords mainly when extracting, but does not support creating AES-encrypted ZIP files. pyzipper supports creating encrypted ZIP files.
  • zf.write(path1, path2)
    path1: source file path to compress
    path2: path inside the ZIP archive
  • pyzipper.AESZipFile
  • Encryption-related parameters
    encryption=pyzipper.WZ_AES (AES encryption)
    zf.setpassword(b"password") (set password)

7z format compression

1
2
3
4
import py7zr

with py7zr.SevenZipFile(dest + '.7z', 'w', password='password') as archive:
    archive.writeall(dest, '')
  • archive.writeall(path1, path2)
    path1: source path to compress (can be a directory)
    path2: target path inside the 7z archive; '' means archive root

  • Encryption parameter
    password='password'

记录并分享
Built with Hugo
Theme Stack designed by Jimmy