Python uses zlib to compress and decompress strings and files,
In python, zlib is used to compress or decompress data for storage and transmission. It is the basis of other compression tools. Next let's take a look at how to use the zlib module to compress and decompress strings and files in python. Let's just look at the sample code.
Example 1: compress and decompress strings
import zlibmessage = 'abcd1234'compressed = zlib.compress(message)decompressed = zlib.decompress(compressed)print 'original:', repr(message)print 'compressed:', repr(compressed)print 'decompressed:', repr(decompressed)
Result
original: 'abcd1234'compressed: 'x\x9cKLJN1426\x01\x00\x0b\xf8\x02U'decompressed: 'abcd1234'
Example 2: compress and decompress a file
import zlibdef 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')
Result
Generate a file
out_decompress.txt out.txt
Problem -- an exception occurred while handling a large object
>>> import zlib>>> 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>", line 1, in <module>OverflowError: size does not fit in an int
Summary
The above is all about zlib compression and decompression of the python module. I hope this article will be helpful for you to learn or use python. If you have any questions, please leave a message, thank you for your support.