加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python用模块zlib压缩与解压字符串和文件的方法

发布时间:2020-12-16 19:54:47 所属栏目:Python 来源:网络整理
导读:python中zlib模块是用来压缩或者解压缩数据,以便保存和传输。它是其他压缩工具的基

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,'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
'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

总结

以上就是关于python模块zlib压缩与解压的全部内容,希望本文的内容对大家学习或者使用python能有一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程小技巧的支持。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读