typestar

Compression and archives in Python

gzip for a stream, zipfile and tarfile for a bundle.

import gzip
import tarfile
import zipfile
from pathlib import Path

Path("one.txt").write_text("hello\n")

with gzip.open("one.txt.gz", "wt") as f:
    f.write("hello\n")
print(gzip.open("one.txt.gz", "rt").read().strip())

with zipfile.ZipFile("bundle.zip", "w", zipfile.ZIP_DEFLATED) as zf:
    zf.write("one.txt")
print(zipfile.ZipFile("bundle.zip").namelist())

with tarfile.open("bundle.tar.gz", "w:gz") as tf:
    tf.add("one.txt")
print(tarfile.open("bundle.tar.gz").getnames())

How it works

  1. gzip.open behaves like open with compression.
  2. A ZipFile is a context manager, in read or write mode.
  3. namelist and getnames show what is inside.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
473
Tokens
154
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 88 seconds.

Type this snippet

Step 3 of 4 in Files & archives, step 28 of 41 in Domain tools.

← Previous Next →