例子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
注:
zlib.compress用于压缩流数据。参数string指定了要压缩的数据流,参数level指定了压缩的级别,它的取值范围是1到9。压缩速度与压缩率成反比,1表示压缩速度最快,而压缩率最低,而9则表示压缩速度最慢但压缩率最高
问题——处理对象过大异常
>>> import zlib
>>> a = ''
>>> b = zlib.compress(a)
>>> b
'x\x9c342\x06\x00\x01-\x00\x97'
>>> a = 'a' * * * *
>>> b = zlib.compress(a)
Traceback (most recent call last):
File "", line , in
OverflowError: size does not fit in an int
python用模块zlib压缩与解压字符串和文件的方法
摘自:http://www.jb51.net/article/100218.htm Python标准模块中,有多个模块用于数据的压缩与解压缩,如zipfile,gzip, bz2等等. python中 ...
Delphi Base64编码_解码及ZLib压缩_解压(转)
最近在写的程序与SOAP相关,所以用到了一些Base64编码/解码及数据压缩/解压方面的知识. 在这里来作一些总结:一.Base64编码/解码 一般用到的是Delphi自带的单元EncdDecd,当然 ...
python的shutil模块-文件的移动、复制、打包、压缩、解压等
参考https://www.cnblogs.com/xiangsikai/p/7787101.html os模块提供了对目录或者文件的新建.删除.查看文件属性,还提供了对文件以及目录的路径操作,比如说 ...
模块讲解----shutil模块(copy、压缩、解压)
作用与功能 主要用于文件的copy,压缩,解压 导入shuitl模块: import shutil copy方法 1.shutil.copyfileobj() 打开file1,并copy写入file ...
常用模块(shutil copy、压缩、解压)
作用与功能 主要用于文件的copy,压缩,解压 导入shuitl模块: import shutil copy方法 1 1.shutil.copyfileobj() 打开file1,并copy写入fi ...
【JNI】OPUS压缩与解压的JNI调用(.DLL版本)
OPUS压缩与解压的JNI调用(.DLL版本) 一.写在开头: 理论上讲,这是我在博客园的第一篇原创的博客,之前也一直想找个地方写点东西,把最近做的一些东西归纳总结下,但是一般工程做完了一高兴就把东西 ...
自定义DelegatingHandler为ASP.NET Web Api添加压缩与解压的功能
HTTP协议中的压缩 Http协议中使用Accept-Encoding和Content-Encoding头来表示期望Response内容的编码和当前Request的内容编码.而Http内容的压缩其实是 ...
【转】iOS开发之压缩与解压文件
ziparchive是基于开源代码”MiniZip”的zip压缩与解压的Objective-C 的Class,使用起来非常的简单方法:从http://code.google.com/p/ziparch ...
iOS开发之压缩与解压文件
ziparchive是基于开源代码”MiniZip”的zip压缩与解压的Objective-C 的Class,使用起来非常的简单 方法:从http://code.google.com/p/ziparc ...
随机推荐
jquery阻止元素冒泡的两种方法
通常情况下,如果给父元素添加事件之后,子元素也会继承同样的事件,这个时候就要阻止子元素的这种行为,成为阻止冒泡,总结两种解决方法: html代码: