Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Files, Paths and Text I/O

The zipfile and tarfile modules

Reference for Python's zipfile and tarfile modules: create, list, read and extract ZIP and TAR archives, in-memory archives, and extraction safety.

An archive bundles many files into one. The zipfile module handles ZIP archives, which compress each file separately and let you jump straight to any member. The tarfile module handles TAR archives (.tar, .tar.gz, .tar.bz2, .tar.xz), the usual format on Linux and macOS, where compression is applied to the whole stream.

Both modules give you a context-managed object that acts like a collection of members. You can write to it, list what it contains, read a member without extracting it, or extract to a folder. Both can also work on file-like objects such as io.BytesIO, which is how the examples here run without touching the disk.

Python
import zipfile

with zipfile.ZipFile("backup.zip", "w", zipfile.ZIP_DEFLATED) as zf:
    zf.write("notes.txt")

Try it

Python A ZIP archive in memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A TAR archive in memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Main API

zipfile

Name Description
ZipFile(file, mode="r", compression=ZIP_STORED) Opens an archive in mode "r", "w" (create), "a" (append) or "x" (create, fail if it exists). file can be a path or file object.
write(filename, arcname=None) Adds a file from disk. arcname sets the name inside the archive.
writestr(name, data) Adds a member from a str or bytes value.
namelist(), infolist() Member names; ZipInfo objects with file_size, compress_size, date_time and more.
read(name), open(name) Whole member as bytes; or a file-like object for streaming.
extract(member, path), extractall(path) Write members to disk.
testzip() Checks CRCs; returns the first bad name or None.
zipfile.is_zipfile(file), BadZipFile Quick check; exception for corrupt archives.

Compression constants: ZIP_STORED (none, the default), ZIP_DEFLATED (the usual choice), plus ZIP_BZIP2 and ZIP_LZMA.

tarfile

Name Description
tarfile.open(name=None, mode="r", fileobj=None) Opens an archive. Modes combine read/write with compression: "r:gz", "w:gz", "w:xz", or "r:*" to detect compression automatically.
add(name, arcname=None, recursive=True) Adds a file or a whole directory tree from disk.
addfile(tarinfo, fileobj) Adds a member from a TarInfo and a file object.
getnames(), getmembers() Names and TarInfo objects.
extractfile(member) File object for reading one regular member (or None for directories).
extract(member, path, filter=...), extractall(path, filter=...) Extract to disk.

Usage notes

  • Never extract untrusted archives blindly. Member names such as ../../etc/passwd or absolute paths can write outside the target folder (the "zip slip" attack). ZipFile.extractall() strips dangerous parts of the name, but you should still check names yourself. For tarfile, pass filter="data"; since Python 3.14 this safer filter is the default, and older versions emit a deprecation warning without it.
  • Zip bombs. A tiny archive can expand to gigabytes. Check file_size totals from infolist() before extracting unknown files.
  • Use with so the archive is closed and the central directory (ZIP) is written. A ZIP that was never closed is corrupt.
  • ZIP members are compressed one by one, so reading one file is fast. A .tar.gz must be decompressed from the start up to the member you need.
  • ZIP defaults to no compression. Pass compression=zipfile.ZIP_DEFLATED explicitly; it needs the zlib module, which every normal Python build has.
  • Text vs bytes. read() returns bytes; call .decode("utf-8") for text. writestr() encodes a str as UTF-8.
  • Single-file compression (a lone .gz or .bz2 file) belongs to the gzip, bz2 and lzma modules. shutil.make_archive() and shutil.unpack_archive() offer a one-line interface for both formats.
  • Encrypted ZIPs. The module can read (but not create) the weak legacy ZIP encryption with setpassword(). Use a different tool if you need real security.