BZ2File

0.98 · maintenance · verified Thu Apr 16

The `bz2file` library provides a file-like object for reading and writing bzip2-compressed files, backporting the `io.BZ2File` interface introduced in Python 3.3. While Python 3.3+ includes `bz2.open()` in its standard library, this standalone package serves as a drop-in replacement or for use with older Python versions (>=2.6, excluding 3.0-3.2). The current version is 0.98. It has an infrequent release cadence, being a stable backport.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create and read a bzip2-compressed file using `BZ2File` in binary mode. It writes byte data, then reads it back to verify integrity.

import os
from bz2file import BZ2File

# Define a temporary file name
file_name = 'example.bz2'
data_to_write = b'This is some data that will be compressed using bzip2.'

# 1. Write compressed data to a .bz2 file
print(f"Writing to {file_name}...")
with BZ2File(file_name, 'wb') as f:
    f.write(data_to_write)
print("Write complete.")

# 2. Read compressed data from the .bz2 file
print(f"Reading from {file_name}...")
with BZ2File(file_name, 'rb') as f:
    read_data = f.read()
print(f"Read data: {read_data}")

assert read_data == data_to_write
print("Data integrity check passed.")

# Clean up the temporary file
os.remove(file_name)
print(f"Cleaned up {file_name}.")

view raw JSON →