最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
python如何用模块zlib压缩与解压字符串和文件
时间:2016-12-16 编辑:简简单单 来源:一聚教程网
python中zlib模块是用来压缩或者解压缩数据,以便保存和传输。它是其他压缩工具的基础。下面来一起看看python用模块zlib压缩与解压字符串和文件的方法。话不多说,直接来看示例代码。
例子1:压缩与解压字符串
importzlib
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:压缩与解压文件
importzlib
defcompress(infile, dst, level=9):
infile=open(infile,'rb')
dst=open(dst,'wb')
compress=zlib.compressobj(level)
data=infile.read(1024)
whiledata:
dst.write(compress.compress(data))
data=infile.read(1024)
dst.write(compress.flush())
defdecompress(infile, dst):
infile=open(infile,'rb')
dst=open(dst,'wb')
decompress=zlib.decompressobj()
data=infile.read(1024)
whiledata:
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
|
问题——处理对象过大异常
>>>importzlib
>>> 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"
OverflowError: size doesnotfitinanint
|
-
上一个: 一聚教程网PHP入门教程05:PHP变量
-
下一个: 怎么利用PHP抓取百度阅读
相关文章
- PHP导出数据超时的优化建议解读 10-31
- PHP之mysql位运算解析 10-31
- Laravel实现登录跳转功能解析 10-31
- php双向队列解读 10-31
- Laravel异常上下文解决教程 10-24
- php数组查询元素位置方法介绍 10-24