Python模块 zlib压缩和解压文件的简单例子/开箱即用

直接用网上的代码最常用的那段代码,但是有BUG,跑不起来,所以改写了一下,包括读写的次数控制,错误的捕获抛出,Python3可以直接跑.

详细代码

import os
import zlib
import math

BUFFER_SIZE = 1024

def compress(infile, dstfile):
    filesize = os.path.getsize(infile)
    read_times = math.ceil(filesize / BUFFER_SIZE)  # 读取次数
    zip = zlib.compressobj(level=9, wbits=15, memLevel=9)

    try:
        dstfile = open(dstfile, "wb")
        with open(filename, "rb") as infile:
            for i in range(read_times):
                zip_buffer = zip.compress(infile.read(BUFFER_SIZE))
                dstfile.write(zip_buffer)
            dstfile.write(zip.flush())
    except:
        raise
    finally:
        dstfile.close()
        return 1


def decompress(zipfile, dstfile):
    filesize = os.path.getsize(zipfile)
    read_times = math.ceil(filesize / BUFFER_SIZE)
    dzip = zlib.decompressobj()

    try:
        dstfile = open(dstfile, "wb")
        with open(zipname, "rb")as zipfile:
            for i in range(read_times):
                file_buffer = dzip.decompress(zipfile.read(BUFFER_SIZE))
                dstfile.write(file_buffer)
    except:
        raise
    finally:
        dstfile.close()
        return 1


if __name__ == '__main__':
    filename = "demo.jpg"
    zipname = "demo.gzip"
    compress(filename, zipname)
    d_zipname = "demo.gzip"
    d_filename = "d_demo.jpg"
    decompress(d_zipname, d_filename)

比较源文件和解压文件的一致性

def check_consistance(filename1, filename2):
    file1_size = os.path.getsize(filename1)
    with open(filename1, "rb") as file1:
        buffer1 = file1.read(file1_size)
    file2_size = os.path.getsize(filename2)
    with open(filename2, "rb") as file2:
        buffer2 = file2.read(file2_size)
    if buffer1 == buffer2:
        return True
    else:
        return False
print(check_consistance(filename,d_filename))  

你可能感兴趣的:(Python,Python,zlib,scripts)