Python zlib module

Python zlib Module

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

This module is the Python implementation of the zlib library, which is part of the GNU Project.

Here is a brief description of the zlib module’s functionality:

compress() Function

This function is one of the module’s primary interfaces and is used in conjunction with the decompress() function. This function returns a bytes object by compressing the data passed to it. This function also has a parameter called level, which controls the degree of compression. It is an integer between 0 and 9. The minimum value 0 indicates no compression, and the maximum value 9 indicates optimal compression. The higher the compression level, the larger the compressed bytes object.

decompress() Function

This function is the inverse of the compress() function. It retrieves uncompressed data. This function can have an optional parameter, wbits, which controls the size of the history buffer and the format of the header and trailer.

The following code uses the compress() function to compress a string object and then decompress it.

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

Output

Compressed: b'xx9cxf3Hxcdxc9xc9Wx08)-
xc9/xcaLxcc)x0exc8xcfxcc+x01x00P/x07xe6'
Decompressed: b'Hello TutorialsPoint'

This module contains definitions for two corresponding compression and decompression objects.

Leave a Reply

Your email address will not be published. Required fields are marked *