Python

Python zipfile — Create, List, Read, and Extract

A zip archive packs several files into one file, often smaller than the parts. Programs build them for downloads, backups, and log bundles, and they read them when an upload or a data feed arrives as a single packed file. This guide creates an archive in code, lists what is inside it, reads entries back without extracting them, adds a file from disk under a chosen name, covers the write, append, and exclusive modes, extracts an archive to a folder, and ends with the missing-name and not-a-zip traps.

Written November 13, 2026 · Tested with Python 3.12.3 · 10 min read

By the end of this guide
  • The main program: create an archive with writestr
  • Listing: infolist, sizes, and compression
  • Reading: read returns bytes, testzip checks the archive
  • Files from disk: write and arcname

Written November 13, 2026

Tested with Python 3.12.3

What this guide is

The zipfile module reads and writes zip archives. An archive holds named entries. Each entry is one file's bytes, stored either as-is or compressed, plus a record of its name and original size. The ZipFile class opens an archive the way open opens a plain file, and the mode letter says what the program may do with it. Entries are named with forward slashes, even on Windows, and a name that ends in a slash is a directory entry, which holds no data. Most work falls into four moves: add entries, list entries, read entries, and extract entries.

The main program: create an archive with writestr

The writestr method adds an entry from data already in memory, so no source file needs to exist on disk first. The name can carry a folder part, and that folder part becomes the entry's place inside the archive:

Python
import pathlib, tempfile, zipfile
with tempfile.TemporaryDirectory() as td:
    archive = pathlib.Path(td) / "notes.zip"
    with zipfile.ZipFile(archive, "w") as z:
        z.writestr("notes.txt", "first line\nsecond line\n")
        z.writestr("data/scores.csv", "name,score\nana,9\n")
    print(archive.exists())
    print(archive.stat().st_size > 0)
    with zipfile.ZipFile(archive) as z:
        print(z.namelist())
        print(len(z.namelist()))

The exact output:

Output
True
True
['notes.txt', 'data/scores.csv']
2

Closing the ZipFile block finishes the archive; an archive read before that close can be incomplete. The namelist call returns the entry names in the order they were added. Reopening with no mode letter opens for reading, which is the default. Text given to writestr is encoded as UTF-8, and bytes can be passed instead when the data is not text.

Listing: infolist, sizes, and compression

The infolist method returns a ZipInfo object per entry, with the stored facts about that entry. The file_size field is the size before packing, and compress_size is the size inside the archive. The compress_type field is 8 for deflated entries and 0 for stored ones:

Python
import pathlib, tempfile, zipfile
text = "ana 9\n" * 50
with tempfile.TemporaryDirectory() as td:
    archive = pathlib.Path(td) / "sizes.zip"
    with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED) as z:
        z.writestr("repeat.txt", text)
        z.writestr("folder/", "")
    with zipfile.ZipFile(archive) as z:
        for info in z.infolist():
            print(info.filename, info.file_size, info.compress_size, info.compress_type, info.is_dir())

The exact output:

Output
repeat.txt 300 12 8 False
folder/ 0 2 8 True

Fifty short repeated lines shrank from 300 bytes to 12, because deflate compression replaces repeated runs with short references. Real text with little repetition shrinks far less, and data that is already compressed, such as images in a compressed format, can stay the same size or grow slightly. The folder entry reports is_dir as True and holds no data; it exists so an extractor can create the folder even when it ends up empty. The compression argument on the opening call sets the default for entries added without their own setting.

Reading: read returns bytes, testzip checks the archive

An entry can be read straight from the archive, with no extraction step. The read method returns bytes, and getinfo returns the ZipInfo for one named entry. The testzip method reads every entry and reports the first damaged one, or None when all entries pass:

Python
import pathlib, tempfile, zipfile
with tempfile.TemporaryDirectory() as td:
    archive = pathlib.Path(td) / "read.zip"
    with zipfile.ZipFile(archive, "w") as z:
        z.writestr("notes.txt", "first line\nsecond line\n")
    with zipfile.ZipFile(archive) as z:
        data = z.read("notes.txt")
        print(type(data).__name__)
        print(data.decode("utf-8"), end="")
        print(z.getinfo("notes.txt").file_size)
        print(z.testzip())

The exact output:

Output
bytes
first line
second line
23
None

Reading in place suits a program that needs one entry, or needs the data as input to the next step, such as parsing a CSV entry with the csv module or loading a JSON entry. Decoding is the caller's job: read never guesses an encoding. A None result from testzip means each entry's stored checksum matched its data. That check covers damage in transit or on disk, and it says nothing about whether the contents are sensible.

Files from disk: write and arcname

The write method adds a file that exists on disk. Without arcname, the entry name is the path as given, minus any leading drive or root. With arcname, the entry takes the given name and the disk layout stays out of the archive:

Python
import pathlib, zipfile
source = pathlib.Path("deep") / "inner" / "report.txt"
source.parent.mkdir(parents=True)
source.write_text("quarterly report\n", encoding="utf-8")
with zipfile.ZipFile("out.zip", "w") as z:
    z.write(source, arcname="report.txt")
    z.write(source)
with zipfile.ZipFile("out.zip") as z:
    print(z.namelist())
    print(z.read("report.txt").decode("utf-8"), end="")

The exact output:

Output
['report.txt', 'deep/inner/report.txt']
quarterly report

The same file landed twice under two names, which shows the rule plainly: the entry name is a label, not a copy of the disk path unless the program leaves it as one. Archives built for other people usually set arcname for every file, so the inside layout is chosen on purpose and does not leak the folder layout of the machine that built the archive. The write method also stores the file's modification time, while writestr entries carry a fixed early date unless a ZipInfo with a chosen date is passed.

Modes: w truncates, a appends, x refuses

The mode letter decides what opening does to an existing archive. Mode w starts fresh and discards any archive already at that path. Mode a adds to the end, keeping the entries that are there. Mode x creates a new archive and fails if the path already exists:

Python
import pathlib, tempfile, zipfile
with tempfile.TemporaryDirectory() as td:
    archive = pathlib.Path(td) / "modes.zip"
    with zipfile.ZipFile(archive, "w") as z:
        z.writestr("a.txt", "a")
    with zipfile.ZipFile(archive, "a") as z:
        z.writestr("b.txt", "b")
    with zipfile.ZipFile(archive) as z:
        print(z.namelist())
    with zipfile.ZipFile(archive, "w") as z:
        z.writestr("only.txt", "x")
    with zipfile.ZipFile(archive) as z:
        print(z.namelist())
    try:
        with zipfile.ZipFile(archive, "x") as z:
            pass
    except FileExistsError as error:
        print(type(error).__name__)

The exact output:

Config
['a.txt', 'b.txt']
['only.txt']
FileExistsError

Append kept both entries, the second w opening dropped both and left only the new one, and x refused to touch the existing file. That refusal is the safe choice for a program that must never overwrite an earlier archive, such as a dated backup. Append has one limit worth knowing: adding an entry whose name is already present does not replace the old entry. The archive then holds two entries with one name, and read returns the later one, so build a fresh archive when an entry must be replaced.

Extracting: extractall and extract

The extractall method unpacks every entry under a target folder, creating folders as needed. The extract method unpacks one named entry and returns the path it wrote:

Python
import pathlib, tempfile, zipfile
with tempfile.TemporaryDirectory() as td:
    root = pathlib.Path(td)
    archive = root / "pack.zip"
    with zipfile.ZipFile(archive, "w") as z:
        z.writestr("notes.txt", "hello zip\n")
        z.writestr("data/scores.csv", "name,score\nana,9\n")
    out = root / "out"
    with zipfile.ZipFile(archive) as z:
        z.extractall(out)
        single = z.extract("notes.txt", root / "one")
    print(sorted(str(p.relative_to(out)) for p in out.rglob("*") if p.is_file()))
    print((out / "notes.txt").read_text(encoding="utf-8"), end="")
    print(pathlib.Path(single).name)
    print((out / "data" / "scores.csv").stat().st_size)

The exact output:

Output
['data/scores.csv', 'notes.txt']
hello zip
notes.txt
17

Extraction rebuilds the folder layout stored in the entry names. Entry names from an archive that came from outside should be treated with care: the module strips drive letters and leading slashes and removes parent-folder parts from names before writing, which keeps extraction inside the target folder on current versions, and a program that builds its own paths from entry names by hand gives that protection up. When a program only needs to look at one entry, read is simpler and leaves no files behind.

Three traps: a missing name, a file that is not a zip, and a repeated name

Trap
Reading a name the archive does not hold raises KeyError. A plain file passed to ZipFile raises BadZipFile, and the is_zipfile function answers the same question with True or False instead of an error:
Python
import pathlib, tempfile, zipfile
with tempfile.TemporaryDirectory() as td:
    root = pathlib.Path(td)
    archive = root / "t.zip"
    with zipfile.ZipFile(archive, "w") as z:
        z.writestr("notes.txt", "data\n")
    with zipfile.ZipFile(archive) as z:
        try:
            z.read("missing.txt")
        except KeyError as error:
            print(type(error).__name__)
    plain = root / "plain.txt"
    plain.write_text("not a zip\n", encoding="utf-8")
    print(zipfile.is_zipfile(plain))
    print(zipfile.is_zipfile(archive))
    try:
        with zipfile.ZipFile(plain) as z:
            pass
    except zipfile.BadZipFile as error:
        print(type(error).__name__)

The exact output:

Output
KeyError
False
True
BadZipFile

The name check comes first in practice, since entry names are case-sensitive and a name stored with a folder part must be asked for with that full part. Testing with is_zipfile suits a program that accepts files from other people and wants a plain rejection message instead of a traceback. The third trap is the repeated name from the modes section: it raises no error — Python only emits a UserWarning (Duplicate name) when the second entry is written — so the lasting sign is a namelist with the same name twice. Checking the namelist before and after an append costs one line and catches it.

Which choice for which job

Job Choice Why
Data in memory writestr No source file needed
File on disk write Stores the file as it is
Set entry name arcname Disk layout stays out
One entry only read No files left behind
Unpack everything extractall Rebuilds the folders
Add to an archive a mode Keeps existing entries
Never overwrite x mode Fails if the file exists
Damaged archive testzip Names the first bad entry

Checklist

  • Before adding a file from disk, set arcname unless the stored path is the path you want readers to see.
  • Before reading an entry, confirm the exact name, folder part included, against namelist.
  • Before appending, check whether the name is already present; a second entry with the same name replaces nothing.
  • Before extracting an archive from outside, let extractall handle the entry names instead of building paths from them by hand.
  • Before trusting an archive that arrived from elsewhere, run testzip or is_zipfile as the job needs.
  • Before choosing compression, check what the data is; deflate helps repeated text and does little for already compressed data.

Sources

  • Python Standard Library, zipfile — ZipFile and its modes, writestr and write with arcname, namelist, infolist and ZipInfo, read and getinfo, testzip, extract and extractall, is_zipfile, and the BadZipFile error.
  • Python Standard Library, pathlib — the Path objects used for the archive path, the source file, and the extraction folders.

Keep Exploring