zoukankan      html  css  js  c++  java
  • 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: 'xx9cKLJN1426x01x00x0bxf8x02U'
    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

    zlib.compress用于压缩流数据。参数string指定了要压缩的数据流,参数level指定了压缩的级别,它的取值范围是1到9。压缩速度与压缩率成反比,1表示压缩速度最快,而压缩率最低,而9则表示压缩速度最慢但压缩率最高

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

    >>> import zlib
    >>> a = '123'
    >>> b = zlib.compress(a)
    >>> b
    'xx9c342x06x00x01-x00x97'
    >>> 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
  • 相关阅读:
    构造方法
    不死神兔
    类与对象
    成员变量和局部变量的区别
    this关键字的理解
    private关键字理解
    如何设置客户端证书
    有关中文的正则表达式
    Web和证书服务:建立电子商务外部网
    认证服务Web 网页循序渐进指南
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/5503179.html
Copyright © 2011-2022 走看看