Python methods for compressing and extracting strings via zlib

Source: Internet
Author: User
The examples in this article describe Python's method of compressing and extracting strings through zlib. Share to everyone for your reference. The implementation method is as follows:

Use zlib.compress to compress strings. Use Zlib.decompress to extract strings. As follows
Copy the Code code as follows:

#coding =utf-8
Import zlib
s = "Hello Word, 00000000000000000000000000000000"
Print Len (s)
c = zlib.compress (s)
Print Len (c)
D = zlib.decompress (c)
Print D



Model Code 2:
Copy CodeThe code is as follows:

Import zlib
message = ' witch which has which witches wrist watch '
compressed = zlib.compress (message)
decompressed = zlib.decompress (compressed)
print ' original: ', repr (message)
print ' compressed: ', repr (compressed)
print ' decompressed: ', repr (decompressed) #输出original: ' Witch which has which witches wrist watch '
Compressed: ' Xx9c+xcf,ixcep (XCFXC8X04X92X19X89XC5PV9H4X15XC8+XCA,. Q (ox04xf2x00d?x0fx89 '
decompressed: ' witch which has which witches wrist watch '


If we were to decompress the string, we could compress the file using Zlib.compressobj and Zlib.decompressobj.
Copy CodeThe code is as follows:

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

Hopefully this article will help you with Python programming.

  • Related Article

    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.