python zlib 压缩与解压

Posted jihite

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python zlib 压缩与解压相关的知识,希望对你有一定的参考价值。

例子1:压缩与解压字符串

import zlib
message = abcd1234
compressed = zlib.compress(message)
decompressed = zlib.decompress(compressed)

print original:, repr(message)
print compressed:, repr(compressed)
print decompressed:, repr(decompressed)

结果

original: abcd1234
compressed: x\x9cKLJN1426\x01\x00\x0b\xf8\x02U
decompressed: abcd1234

例子2:压缩与解压文件

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(in.txt, out.txt)
    decompress(out.txt, out_decompress.txt)

结果

生成文件

out_decompress.txt  out.txt

问题——处理对象过大异常

>>> import zlib
>>> a = 123
>>> b = zlib.compress(a)
>>> b
x\x9c342\x06\x00\x01-\x00\x97
>>> a = a * 1024 * 1024 * 1024 * 10
>>> b = zlib.compress(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: size does not fit in an int

 

以上是关于python zlib 压缩与解压的主要内容,如果未能解决你的问题,请参考以下文章

C++ 基于ZLIB压缩库的数据或文件的压缩与解压缩小程序

解压后如何取回原来的字符串 - Zlib

Python之zlib模块的使用

iOS开发之压缩与解压文件

Python zlib 解压缩 gzipped 数据

VC++使用zlib压缩及解压数据,使用base64编码及解码数据(附源码)