# Python Bz2 Module

The `bz2` module provides a comprehensive interface for the bzip2 compression algorithm. It implements a complete file interface, one-shot (de)compression functions, and types for sequential (de)compression.

## Importing the Module

```python
import bz2
```

## Reading Compressed Files

To open a bzip2-compressed file for reading, use `bz2.open()`.

```python
import bz2

with bz2.open('file.txt.bz2', 'rt') as f:
    file_content = f.read()
    print(file_content)
```

## Writing Compressed Files

To open a bzip2-compressed file for writing, use `bz2.open()` with mode `'wt'` (for text) or `'wb'` (for binary).

```python
import bz2

content = "Hello, world!"
with bz2.open('file.txt.bz2', 'wt') as f:
    f.write(content)
```

## Compressing Data

You can compress data directly using `bz2.compress()`.

```python
import bz2

data = b"Hello, world!"
compressed_data = bz2.compress(data)
print(compressed_data)
```

## Decompressing Data

You can decompress data using `bz2.decompress()`.

```python
decompressed_data = bz2.decompress(compressed_data)
print(decompressed_data)
```

[[programming/python/python]]