Detailed explanation of the method code of Python using the module zlib to compress and decompress strings and files

高洛峰
Release: 2017-03-24 17:39:58
Original
1705 people have browsed it

The zlib module in python is used to compress or decompress data for saving and transmission. It is the basis for other compression tools. Let's take a look at how Python uses the zlib module to compress and decompress strings and files. Without further ado, let’s look directly 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)
Copy after login


Result

original: 'abcd1234'
compressed: 'x\x9cKLJN1426\x01\x00\x0b\xf8\x02U'
decompressed: 'abcd1234'
Copy after login


Example 2: Compressed and decompressed 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')
Copy after login


Result
Generated file

out_decompress.txt out.txt
Copy after login


Problem - Processing 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 * 10
>>> b = zlib.compress(a)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
OverflowError: size does not fit in an int
Copy after login


The above is the detailed content of Detailed explanation of the method code of Python using the module zlib to compress and decompress strings and files. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!