xopen: Open Compressed Files Transparently

2.0.2 · active · verified Sat Apr 11

This Python module provides an `xopen` function that works like Python's built-in `open` function but also transparently deals with compressed files. `xopen` selects the most efficient method for reading or writing a compressed file, often leveraging external tools like `pigz` for parallel processing. It supports gzip (.gz), bzip2 (.bz2), xz (.xz), and optionally Zstandard (.zst) formats. The library is actively maintained, currently at version 2.0.2, and has a consistent release cadence.

Warnings

Install

Imports

Quickstart

Demonstrates reading from a gzipped file (auto-detected) and writing to an xz-compressed file with a specified compression level. `xopen` behaves like the built-in `open` but handles compression transparently based on file extension or magic numbers.

from xopen import xopen
import os

# Create a dummy gzipped file
with open('example.txt', 'w') as f:
    f.write('Hello, world!\nThis is a test.')
import gzip
with open('example.txt', 'rb') as f_in:
    with gzip.open('example.txt.gz', 'wb') as f_out:
        f_out.write(f_in.read())
os.remove('example.txt') # Clean up uncompressed file

# Open for reading (auto-detects gzip)
with xopen('example.txt.gz', mode='rt') as f:
    content = f.read()
    print(f'Read content: {content.strip()}')

# Open for writing (creates xz compressed file)
output_file = 'output.txt.xz'
with xopen(output_file, mode='wt', compresslevel=3) as f:
    f.write('This is compressed with xz.\nAnother line.')

# Verify writing (optional: requires another xopen to read it back)
with xopen(output_file, mode='rt') as f:
    written_content = f.read()
    print(f'Written content to {output_file}: {written_content.strip()}')

# Clean up generated files
os.remove('example.txt.gz')
os.remove(output_file)

view raw JSON →