The zlib Module



If your application requires data compression, the functions in this module can be used to perform compression and decompression.

This module is a Python implementation of zlib library, which is a part of GNU project.

Here is a brief discussion of the functionality of the zlib module −

compress() function

This function is the primary interface to this module along with decompress() function. This function returns byte object by compressing the data given to it as parameter. The function has another parameter called level which controls the extent of compression. It an integer between 0 to 9. Lowest value 0 stands for no compression and 9 stands for best compression. Higher the level of compression, greater the length of compressed byte object.

decompress() function

This function does the opposite of compress() function. It retrieves the uncompressed data. This function can have an optional parameter called wbits which controls the size of history buffer and the nature of header and trailer format.

Following code compresses a string object with the help of compress() function and decompresses it back.

import zlib
data = b'Hello TutorialsPoint'
compressed = zlib.compress(data)
print ("Compressed:",compressed)
decompressed = zlib.decompress(compressed)
print ("Decompressed:", decompressed)

Output

Compressed: b'x\x9c\xf3H\xcd\xc9\xc9W\x08)-
\xc9/\xcaL\xcc)\x0e\xc8\xcf\xcc+\x01\x00P/\x07\xe6'
Decompressed: b'Hello TutorialsPoint'

The module consists of definitions of has two corresponding classes of compression and decompression objects.

python_data_compression.htm
Advertisements