python使用zlib压缩和解压文件

import zlib


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


if __name__ == "__main__":
    compress('test.txt', 'test.gz')
    decompress('test.gz', 'test.dat')

注:zlib设置压缩等级,zlib压缩等级为1-9,数值越大压缩比越高,压缩速度越慢,默认为6

猜你喜欢

转载自blog.csdn.net/qq_34474071/article/details/123871812