On this page
  1. bz2
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Streaming Multistream .bz2 Files Without Full Extraction
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

bz2

Prev: builtins | Up: stdlib_module | Next: cProfile
Rel: pickle, copyreg, shelve, marshal, dbm
Ref: docs.python.org — bz2
Tags: #public #python3 #stdlib


Import

import bz2

Overview

bzip2 compression and decompression (compress, decompress, open, BZ2File, BZ2Decompressor), widely used for Wikipedia multistream dumps (.xml.bz2) and legacy .tar.bz2 archives. Supports reading concatenated multistream .bz2 blocks natively.

Quick Start

import bz2

raw = b"wikipedia dump excerpt " * 100
compressed = bz2.compress(raw, compresslevel=9)
assert len(compressed) < len(raw)
assert bz2.decompress(compressed) == raw

Implementation Walkthrough

1. Streaming Multistream .bz2 Files Without Full Extraction

import bz2
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    p = Path(tmp) / "sample.txt.bz2"
    with bz2.open(p, "wt", encoding="utf-8") as fh:
        fh.write("article 1\narticle 2\n")
    with bz2.open(p, "rt", encoding="utf-8") as fh:
        assert fh.read().splitlines() == ["article 1", "article 2"]

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes