Python USES zlib to compress and extract strings

  • 2020-04-02 14:21:14
  • OfStack

This article illustrates how python can compress and extract strings through zlib. Share with you for your reference. The specific implementation method is as follows:

Use zlib.press to compress strings. Decompress can be used to decompress strings. The following

#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

 
Demonstration code 2:
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) # The output 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 want to decompress a string, we can use zlib.compressobj and zlib.decompressobj to decompress the file
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())

I hope this article has helped you with your Python programming.


Related articles: