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

yipeiwu_com6年前Python基础

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: '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压缩与解压的全部内容,希望本文的内容对大家学习或者使用python能有一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

python实现rsa加密实例详解

python实现rsa加密实例详解 一 代码 import rsa key = rsa.newkeys(3000)#生成随机秘钥 privateKey = key[1]#私钥 pu...

浅谈Python中的数据类型

数据类型: float — 浮点数可以精确到小数点后面15位 int — 整型可以无限大 bool — 非零为true,零为false list — 列表 Float/Int: 运...

Selenium定位元素操作示例

本文实例讲述了Selenium定位元素操作。分享给大家供大家参考,具体如下: Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在...

Python 模拟登陆的两种实现方法

Python 模拟登陆的两种实现方法 有时候我们的抓取项目时需要登陆到某个网站上,才能看见某些内容的,所以模拟登陆功能就必不可少了,散仙这次写的文章,主要有2个例子,一个是普通写法写的,...

解决Python 遍历字典时删除元素报异常的问题

错误的代码① d = {'a':1, 'b':0, 'c':1, 'd':0} for key, val in d.items(): del(d[k]) 错误的代码② --...