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
Import zlib 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
Import zlib
def compress (infile, DST, level=9):
infile = open (infile, ' RB ')
DST = open (DST, ' WB '
) Compress = Zlib.compressobj (level)
data = Infile.read (1024) while
data:
dst.write (Compress.compress ( Data)
data = Infile.read (1024)
Dst.write (Compress.flush ())
def decompress (infile, DST):
infile = Open (infile, ' RB ')
DST = open (DST, ' WB ')
decompress = Zlib.decompressobj ()
data = Infile.read (1024) While
data:
dst.write (decompress.decompress (data))
data = Infile.read (1024)
Dst.write ( Decompress.flush ())
if __name__ = = "__main__": 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
>>> import zlib
>>> a = ' 123 '
>>> B = zlib.compress (a)
>>> b
' x\ X9c342\x06\x00\x01-\x00\x97 '
>>> a = ' a ' * 1024 * 1024 * 1024 *
>>> B = zlib.compress (a)
Traceback (most recent):
File "<stdin>", line 1, in <module>
overflowerror:size does not fi T in an int
Summarize
The above is about Python module zlib compression and decompression of the entire content, I hope the content of this article for everyone to learn or use Python can have some help, if there is doubt you can message exchange, thank you for the cloud Habitat Community support.