How do I read and write gzip/bz2/xz compressed files?

Reading and writing compressed files in Python can be easily handled using the built-in libraries. Below are examples for gzip, bz2, and xz formats.

Keywords: Python, gzip, bz2, xz, compressed files, read, write
Description: This guide provides examples of how to read and write files that are compressed using gzip, bz2, and xz formats in Python.

# Example: Reading and writing Gzip compressed files
import gzip

# Writing to a gzip file
with gzip.open('example.txt.gz', 'wt') as f:
    f.write('This is an example of writing to a gzip file.\n')

# Reading from a gzip file
with gzip.open('example.txt.gz', 'rt') as f:
    content = f.read()
    print(content)

# Example: Reading and writing Bz2 compressed files
import bz2

# Writing to a bz2 file
with bz2.open('example.txt.bz2', 'wt') as f:
    f.write('This is an example of writing to a bz2 file.\n')

# Reading from a bz2 file
with bz2.open('example.txt.bz2', 'rt') as f:
    content = f.read()
    print(content)

# Example: Reading and writing Xz compressed files
import lzma

# Writing to an xz file
with lzma.open('example.txt.xz', 'wt') as f:
    f.write('This is an example of writing to an xz file.\n')

# Reading from an xz file
with lzma.open('example.txt.xz', 'rt') as f:
    content = f.read()
    print(content)
    

Keywords: Python gzip bz2 xz compressed files read write