How python compresses and extracts strings and files using module zlib

Source: Internet
Author: User

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

Importzlib
Defcompress (infile, DST, level=9):
Infile=open (infile, ' RB ')
Dst=open (DST, ' WB ')
Compress=zlib.compressobj (Level)
Data=infile.read (1024)
Whiledata:
Dst.write (compress.compress (data))
Data=infile.read (1024)
Dst.write (Compress.flush ())
Defdecompress (infile, DST):
Infile=open (infile, ' RB ')
Dst=open (DST, ' WB ')
Decompress=zlib.decompressobj ()
Data=infile.read (1024)
Whiledata:
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

>>>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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.