Python uses zlib to compress and decompress strings

Source: Internet
Author: User
This article describes how to use zlib to compress and decompress strings in python. It also describes the usage of zlib and how to use zlib. compressobj and zlib. decompressobj is used to compress and decompress files. For more information about how to compress and decompress strings using zlib, see the following example. Share it with you for your reference. The specific implementation method is as follows:

Use zlib. compress to compress strings. Use zlib. decompress to extract strings. As follows:

The code is 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



Demo code 2:

The 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) # output original: 'witch which has which witches wrist watch'
Compressed: 'xx9c + xcf, IxceP (xcfxc8x04x92x19x89xc5PV9H4x15xc8 + xca,. Q (Ox04xf2x00D? X0fx89'
Decompressed: 'WC which has which witches wrist watch'


To decompress the string, use zlib. compressobj and zlib. decompressobj to compress and decompress the file.

The 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 (1, 1024)
While data:
Dst. write (compress. compress (data ))
Data = infile. read (1, 1024)
Dst. write (compress. flush ())
Def decompress (infile, dst ):
Infile = open (infile, 'RB ')
Dst = open (dst, 'WB ')
Decompress = zlib. decompressobj ()
Data = infile. read (1, 1024)
While data:
Dst. write (decompress. decompress (data ))
Data = infile. read (1, 1024)
Dst. write (decompress. flush ())

I hope this article will help you with Python programming.

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.