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.
import zipfile with zipfile.ZipFile("backup.zip", "w", zipfile.ZIP_DEFLATED) as zf: zf.write("notes.txt")
Try it
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.
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/passwdor 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. Fortarfile, passfilter="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_sizetotals frominfolist()before extracting unknown files. - Use
withso 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.gzmust be decompressed from the start up to the member you need. - ZIP defaults to no compression. Pass
compression=zipfile.ZIP_DEFLATEDexplicitly; it needs thezlibmodule, which every normal Python build has. - Text vs bytes.
read()returnsbytes; call.decode("utf-8")for text.writestr()encodes astras UTF-8. - Single-file compression (a lone
.gzor.bz2file) belongs to thegzip,bz2andlzmamodules.shutil.make_archive()andshutil.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.
Related
gzip,bz2andlzma,shutil,pathlib,io.BytesIO- Lessons: Files, os and shutil, pathlib