zoukankan      html  css  js  c++  java
  • python用模块zlib压缩与解压字符串和文件的方法

    摘自:http://www.jb51.net/article/100218.htm

    Python标准模块中,有多个模块用于数据的压缩与解压缩,如zipfile,gzip, bz2等等。

    python中zlib模块是用来压缩或者解压缩数据,以便保存和传输。它是其他压缩工具的基础。下面来一起看看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

  • 相关阅读:
    Spring MVC多动作控制器
    Spring MVC简单URL处理程序映射
    Spring MVC控制器类名称处理映射
    Spring MVC文件上传处理
    再探Tomcat
    Git教程之工作区和暂存区
    linux系统启动级别
    浅析JAVA_HOME,CLASSPATH和PATH的作用
    *Linux之rm命令
    @CentOS环境下Java开发环境的搭建
  • 原文地址:https://www.cnblogs.com/gwind/p/8266009.html
Copyright © 2011-2022 走看看