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.