The zlib module in Python is used to compress or decompress data for storage and transmission. It is the basis for other compression tools. Let's take a look at Python's method of compressing and decompressing strings and files using module zlib. If you don't say more, just look at the sample code.
Example 1: compressing and decompressing strings
Importzlib
Message= ' abcd1234 '
Compressed=zlib.compress (Message)
Decompressed=zlib.decompress (compressed)
print ' original: ', repr (message)
print ' compressed: ', repr (compressed)
print ' decompressed: ', repr (decompressed)
|
Results
Original: ' abcd1234 '
Compressed: ' X\X9CKLJN1426\X01\X00\X0B\XF8\X02U '
decompressed: ' abcd1234 '
|
Example 2: compressing and extracting files
Defcompress (infile, DST, level=9):
Infile=open (infile, ' RB ')
Compress=zlib.compressobj (Level)
Dst.write (compress.compress (data))
Dst.write (Compress.flush ())
Defdecompress (infile, DST):
Infile=open (infile, ' RB ')
Decompress=zlib.decompressobj ()
Dst.write (decompress.decompress (data))
Dst.write (Decompress.flush ())
Compress (' in.txt ', ' OUT.txt ')
Decompress (' OUT.txt ', ' out_decompress.txt ')
|
Results
Generating files
Out_decompress.txt OUT.txt
|
Problem-handling object too large exception
>>>importzlib
>>> a= ' 123 '
>>> B=zlib.compress (a)
>>> b
' X\x9c342\x06\x00\x01-\x00\x97 '
>>> a= ' a ' *1024*1024*1024*10
>>> B=zlib.compress (a)
Traceback (most recent call last):
File "<stdin>", line1,in<module>
Overflowerror:size Doesnotfitinanint
|