python使用zlib模块实现压缩与解压缩

发布时间:2019-08-10编辑:脚本学堂
介绍下python模块zlib的用法,学习下使用python中的zlib模块进行压缩与解压缩的方法,有需要的朋友参考下。

问题:如何使用zlib模块来进行压缩解压了?
解答:
1.使用zlib.compress可以压缩字符串。使用zlib.decompress可以解压字符串。
压缩解压字符串示范代码:
 

复制代码 代码示例:
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'

2.使用zlib.compressobj和zlib.decompressobj比较适合用于对文件进行压缩解压。
以下定义的两个函数,使用zlib.compressobj和zlib.decompressobj对文件进行压缩、解压缩的例子:
 

复制代码 代码示例:
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())