Open In App

bz2 Module in Python

Last Updated : 12 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

bz2 module in Python provides support for compressing and decompressing data using the bzip2 compression algorithm. It allows handling .bz2 files and compressing / decompressing byte data efficiently. For example:

Python
import bz2

# Data to compress
s = b"Hello, BZ2 Compression!"

# Compressing the data
c = bz2.compress(s)
print(c)

# Decompressing the data
d = bz2.decompress(c)
print(d)

Output
b"BZh91AY&SY\xb7\x0eq\x95\x00\x00\x03\x9f\x80`\x04\x10\x00\x18@\x00\x10\x02'\xd8\x00 \x001CM0\x00D\r=OQ\x82c,\xe5S`\xcd4\x14\xbb\xc4\xd0\x1f\x17rE8P\x90\xb7\x0eq\x95"
b'Hello, BZ2 Compression!'

Explanation:

  • bz2.compress() function compresses the given byte data.
  • bz2.decompress() function restores the original data from the compressed form.

Syntax of bz2

bz2.compress(data, compresslevel=9)
bz2.decompress(data)

Parameters:

  • data: The byte data to be compressed or decompressed.
  • compresslevel (optional): An integer from 1 (fastest, less compression) to 9 (slowest, best compression). Default is 9.

Return Type: Returns compressed or decompressed byte data.

Compressing Data with bz2

bz2 module allows compressing large byte data efficiently, reducing storage and transmission size.

Python
import bz2

# Original data
d = b"Python bz2 module example."

# Compressing data
cd = bz2.compress(d)
print(cd)

Output
b'BZh91AY&SY\xe7\x8c\xf4\xc3\x00\x00\x02\x9b\x80@\x01\x10\x00@\x006G\xc6p \x00"\x9a\r\x03\x11\xe5\nd\xc4\xc823\x99\xb2\x1b\x85\x87\x95<\x05]@B`\x1f\x8b\xb9"\x9c(Hs\xc6za\x80'

Explanation: bz2.compress() function compresses the byte string, making it smaller for storage or transfer.

Decompressing Data with bz2

bz2.decompress() method is used to restore the original data from its compressed state.

Python
import bz2

# Compressed data
c = bz2.compress(b"Data to be restored")

# Decompressing
o = bz2.decompress(c)
print(o)

Output
b'Data to be restored'

Explanation: bz2.decompress() converts the compressed byte data back to its original form, ensuring no data loss.


Next Article
Article Tags :
Practice Tags :

Similar Reads