If you can use python 3, there is a useful library, py7zr, which supports 7zip archive compression, decompression, encryption and decryption.

import py7zr
with py7zr.SevenZipFile('sample.7z', mode='r') as z:
    z.extractall()
Answer from Zhou Hongbo on Stack Overflow
Top answer
1 of 7
27

If you can use python 3, there is a useful library, py7zr, which supports 7zip archive compression, decompression, encryption and decryption.

import py7zr
with py7zr.SevenZipFile('sample.7z', mode='r') as z:
    z.extractall()
2 of 7
7

I ended up in this situation where I was forced to use 7z, and also needed to know exactly which files were extracted from each zip archive. To deal with this, you can check the output of the call to 7z and look for the filenames. Here's what the output of 7z looks like:

$ 7z l sample.zip

7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,8 CPUs x64)

Scanning the drive for archives:
1 file, 472 bytes (1 KiB)

Listing archive: sample.zip

--
Path = sample.zip
Type = zip
Physical Size = 472

   Date      Time    Attr         Size   Compressed  Name
------------------- ----- ------------ ------------  ------------------------
2018-12-01 17:09:59 .....            0            0  sample1.txt
2018-12-01 17:10:01 .....            0            0  sample2.txt
2018-12-01 17:10:03 .....            0            0  sample3.txt
------------------- ----- ------------ ------------  ------------------------
2018-12-01 17:10:03                  0            0  3 files

and how to parse that output with python:

import subprocess

def find_header(split_line):
    return 'Name' in split_line and 'Date' in split_line

def all_hyphens(line):
    return set(line) == set('-')

def parse_lines(lines):
    found_header = False
    found_first_hyphens = False
    files = []
    for line in lines:

        # After the header is a row of hyphens
        # and the data ends with a row of hyphens
        if found_header:
            is_hyphen = all_hyphens(''.join(line.split()))

            if not found_first_hyphens:
                found_first_hyphens = True
                # now the data starts
                continue

            # Finding a second row of hyphens means we're done
            if found_first_hyphens and is_hyphen:
                return files

        split_line = line.split()

        # Check for the column headers
        if find_header(split_line):
            found_header=True
            continue

        if found_header and found_first_hyphens:
            files.append(split_line[-1])
            continue

    raise ValueError("We parsed this zipfile without finding a second row of hyphens")



byte_result=subprocess.check_output('7z l sample.zip', shell=True)
str_result = byte_result.decode('utf-8')
line_result = str_result.splitlines()
files = parse_lines(line_result)
🌐
Python
docs.python.org › 3 › library › zipfile.html
zipfile — Work with ZIP archives
February 23, 2026 - Source code: Lib/zipfile/ The ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this ...
🌐
PyPI
pypi.org › project › py7zr
py7zr · PyPI
January 18, 2026 - from py7zr import pack_7zarchive, unpack_7zarchive import shutil # register file format at first. shutil.register_archive_format('7zip', pack_7zarchive, description='7zip archive') shutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive) # extraction shutil.unpack_archive('test.7z', '/tmp') # compression shutil.make_archive('target', '7zip', 'src') py7zr uses a python3 standard lzma module for extraction and compression.
      » pip install py7zr
    
Published   Dec 21, 2025
Version   1.1.0
🌐
Readthedocs
py7zr.readthedocs.io › en › latest › user_guide.html
User Guide — py7zr – 7-zip archive library
If you want to extract a 7z archive into the specified directory, use the x subcommand: $ python -m py7zr x monty.7z target-dir/ $ py7zr x monty.7z
🌐
Quora
quora.com › How-can-I-write-a-Python-program-to-unzip-a-7z-archive-protected-with-a-password
How to write a Python program to unzip a 7z archive protected with a password - Quora
so you can using the standard library and 3 lines of code to extract all of the files (and subdirectories) of a zipfile to a target directory. I do not understand why at least one answer thinks that this isn’t possible in Python: clearly it is. The ‘extractall(…)’ method has parameters to limit which members of the zip file are extract, and provide passwords for encrypted files. ... Your website. No coding required. No coding needed. WordPress.com gives you everything to build, grow, and own your site. ... I forgot my .7z file password.
🌐
Readthedocs
py7zr.readthedocs.io
py7zr – a 7z library on python — py7zr – 7-zip archive library
Stream 7z content · Example to extract into network storage · Security Policy · Supported Versions · Reporting a Vulnerability · API Documentation · py7zr — 7-Zip archive library · Bad7zFile · FileInfo · is_7zfile() unpack_7zarchive() pack_7zarchive() Class description ·
🌐
Python Module of the Week
pymotw.com › 2 › zipfile
zipfile – Read and write ZIP archive files - Python Module of the Week
Since version 2.3 Python has had the ability to import modules from inside ZIP archives if those archives appear in sys.path. The PyZipFile class can be used to construct a module suitable for use in this way. When you use the extra method writepy(), PyZipFile scans a directory for .py files and adds the corresponding .pyo or .pyc file to the archive. If neither compiled form exists, a .pyc file is created and added. import sys import zipfile if __name__ == '__main__': zf = zipfile.PyZipFile('zipfile_pyzipfile.zip', mode='w') try: zf.debug = 3 print 'Adding python files' zf.writepy('.') finally: zf.close() for name in zf.namelist(): print name print sys.path.insert(0, 'zipfile_pyzipfile.zip') import zipfile_pyzipfile print 'Imported from:', zipfile_pyzipfile.__file__
Find elsewhere
🌐
GitHub
github.com › zyrikby › 7z2zip_converter
GitHub - zyrikby/7z2zip_converter: Converter from 7z to zip archives
This utility is created to convert 7z archive into ordinary zip archive with which it is possible to work using Python's zipfile module without unarchiving. The difference of this util from other tools is that it extracts and zips files from ...
Starred by 5 users
Forked by 6 users
Languages   Python 100.0% | Python 100.0%
🌐
Readthedocs
py7zr.readthedocs.io › en › latest › api.html
API Documentation — py7zr – 7-zip archive library
filter_pattern = re.compile(r'scripts.*') with SevenZipFile('archive.7z', 'r') as zip: allfiles = zip.getnames() targets = [f if filter_pattern.match(f) for f in allfiles] with SevenZipFile('archive.7z', 'r') as zip: zip.extract(targets=targets) with SevenZipFile('archive.7z', 'r') as zip: zip.extract(targets=targets, recursive=True)
🌐
Aspose
blog.aspose.com › aspose.blogs › read 7zip archives in python
Read 7zip Archives in Python | Python py7zr Alternate
September 13, 2023 - Aspose.ZIP for Python provides a convenient and efficient way to work with 7zip archives in Python applications. In this blog post, we explored how to read the content of a 7zip archive in Python. We also covered how to read a password-protected 7zip archive.
🌐
GitHub
github.com › miurahr › py7zr
GitHub - miurahr/py7zr: 7zip in python3 with ZStandard, PPMd, LZMA2, LZMA1, Delta, BCJ, BZip2, and Deflate compressions, and AES encryption. · GitHub
from py7zr import pack_7zarchive, unpack_7zarchive import shutil # register file format at first. shutil.register_archive_format('7zip', pack_7zarchive, description='7zip archive') shutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive) # extraction shutil.unpack_archive('test.7z', '/tmp') # compression shutil.make_archive('target', '7zip', 'src') py7zr uses a python3 standard lzma module for extraction and compression.
Starred by 537 users
Forked by 89 users
Languages   Python 97.5% | Shell 2.2% | C 0.3%
🌐
GitHub
github.com › topics › 7zip
Build software better, together
July 16, 2020 - gzip zip extractor extract tar cab bzip2 decompression archive zstd lzma iso9660 xz libarchive 7zip cpio ... A wrapper based on bit7z. ... Simple python script that allow us brute-forcing 7z and zip files.
🌐
GitHub
github.com › UuuNyaa › x7zipfile
GitHub - UuuNyaa/x7zipfile: x7zipfile is a thin 7-zip command wrapper for Python.
import x7zipfile with x7zipfile.x7ZipFile('myarchive.7z') as zipfile: for info in zipfile.infolist(): print(info.filename, info.file_size) if info.filename == 'README': zipfile.extract(info)
Author   UuuNyaa
🌐
Note.nkmk.me
note.nkmk.me › home › python
Zip and Unzip Files in Python: zipfile, shutil | note.nkmk.me
August 13, 2023 - If zipfile or pyzipper don't work ... management — Python 3.11.4 documentation · For example, use the 7z command of 7-zip (installation required)....
🌐
Snyk
snyk.io › advisor › py7zr › py7zr code examples
Top 5 py7zr Code Examples | Snyk
from_path (str): path of the archive to_path (str): path to the directory of extracted files Returns: path to the directory of extracted files """ extenstion = ''.join(Path(from_path).suffixes) if extenstion == '.zip': with zipfile.ZipFile(from_path, 'r') as zfile: zfile.extractall(to_path) elif extenstion == '.tar.gz' or extenstion == '.tgz': with tarfile.open(from_path, 'r:gz') as tgfile: for tarinfo in tgfile: tgfile.extract(tarinfo, to_path) elif extenstion == '.7z': szfile = py7zr.SevenZipFile(from_path, mode='r') szfile.extractall(path=to_path) szfile.close() return Path(to_path) miurahr / aqtinstall / aqt / installer.py View on Github ·
🌐
Random Engineering
dustinoprea.com › 2014 › 04 › 17 › writing-and-reading-7-zip-from-python
Writing and Reading 7-Zip Archives From Python | Random Engineering
February 8, 2016 - import libarchive with libarchive.reader('test.7z') as reader: for e in reader: # (The entry evaluates to a filename.) print("> %s" % (e))
🌐
Real Python
realpython.com › python-zipfile
Python's zipfile: Manipulate Your ZIP Files Efficiently – Real Python
January 26, 2025 - Note: Python’s zipfile supports decryption. However, it doesn’t support the creation of encrypted ZIP files. That’s why you would need to use an external file archiver to encrypt your files. Some popular file archivers include 7z and WinRAR for Windows, Ark and GNOME Archive Manager for Linux, and Archiver for macOS.