==zlib 模块==

(可选) ``zlib`` 模块为 "zlib" 压缩提供支持. (这种压缩方法是 "deflate".) 

[Example 2-43 #eg-2-43] 展示了如何使用 ``compress`` 和 ``decompress`` 函数接受字符串参数.

====Example 2-43. 使用 zlib 模块压缩字符串====[eg-2-43]

```
File: zlib-example-1.py import zlib MESSAGE = "life of brian" compressed_message = zlib.compress(MESSAGE)
decompressed_message = zlib.decompress(compressed_message) print "original:", repr(MESSAGE)
print "compressed message:", repr(compressed_message)
print "decompressed message:", repr(decompressed_message) *B*original: 'life of brian'
compressed message: 'x\234\313\311LKU\310OSH*\312L\314\003\000!\010\004\302'
decompressed message: 'life of brian'*b*
``` 文件的内容决定了压缩比率, [Example 2-44 #eg-2-44] 说明了这点. ====Example 2-44. 使用 zlib 模块压缩多个不同类型文件====[eg-2-44] ```
File: zlib-example-2.py import zlib
import glob for file in glob.glob("samples/*"): indata = open(file, "rb").read()
outdata = zlib.compress(indata, zlib.Z_BEST_COMPRESSION) print file, len(indata), "=>", len(outdata),
print "%d%%" % (len(outdata) * 100 / len(indata)) *B*samples\sample.au 1676 => 1109 66%
samples\sample.gz 42 => 51 121%
samples\sample.htm 186 => 135 72%
samples\sample.ini 246 => 190 77%
samples\sample.jpg 4762 => 4632 97%
samples\sample.msg 450 => 275 61%
samples\sample.sgm 430 => 321 74%
samples\sample.tar 10240 => 125 1%
samples\sample.tgz 155 => 159 102%
samples\sample.txt 302 => 220 72%
samples\sample.wav 13260 => 10992 82%*b*
``` 你也可以实时地压缩或解压缩数据, 如 [Example 2-45 #eg-2-45] 所示. ====Example 2-45. 使用 zlib 模块解压缩流====[eg-2-45] ```
File: zlib-example-3.py import zlib encoder = zlib.compressobj() data = encoder.compress("life")
data = data + encoder.compress(" of ")
data = data + encoder.compress("brian")
data = data + encoder.flush() print repr(data)
print repr(zlib.decompress(data)) *B*'x\234\313\311LKU\310OSH*\312L\314\003\000!\010\004\302'
'life of brian'*b*
``` [Example 2-46 #eg-2-46] 把解码对象封装到了一个类似文件对象的类中,
实现了一些文件对象的方法, 这样使得读取压缩文件更方便. ====Example 2-46. 压缩流的仿文件访问方式====[eg-2-46] ```
File: zlib-example-4.py import zlib
import string, StringIO class ZipInputStream: def _ _init_ _(self, file):
self.file = file
self._ _rewind() def _ _rewind(self):
self.zip = zlib.decompressobj()
self.pos = 0 # position in zipped stream
self.offset = 0 # position in unzipped stream
self.data = "" def _ _fill(self, bytes):
if self.zip:
# read until we have enough bytes in the buffer
while not bytes or len(self.data) < bytes:
self.file.seek(self.pos)
data = self.file.read(16384)
if not data:
self.data = self.data + self.zip.flush()
self.zip = None # no more data
break
self.pos = self.pos + len(data)
self.data = self.data + self.zip.decompress(data) def seek(self, offset, whence=0):
if whence == 0:
position = offset
elif whence == 1:
position = self.offset + offset
else:
raise IOError, "Illegal argument"
if position < self.offset:
raise IOError, "Cannot seek backwards" # skip forward, in 16k blocks
while position > self.offset:
if not self.read(min(position - self.offset, 16384)):
break def tell(self):
return self.offset def read(self, bytes = 0):
self._ _fill(bytes)
if bytes:
data = self.data[:bytes]
self.data = self.data[bytes:]
else:
data = self.data
self.data = ""
self.offset = self.offset + len(data)
return data def readline(self):
# make sure we have an entire line
while self.zip and "\n" not in self.data:
self._ _fill(len(self.data) + 512)
i = string.find(self.data, "\n") + 1
if i <= 0:
return self.read()
return self.read(i) def readlines(self):
lines = []
while 1:
s = self.readline()
if not s:
break
lines.append(s)
return lines #
# try it out data = open("samples/sample.txt").read()
data = zlib.compress(data) file = ZipInputStream(StringIO.StringIO(data))
for line in file.readlines():
print line[:-1] *B*We will perhaps eventually be writing only small
modules which are identified by name as they are
used to build larger ones, so that devices like
indentation, rather than delimiters, might become
feasible for expressing local structure in the
source language.
-- Donald E. Knuth, December 1974*b*
```

python标准库介绍——29 zlib 模块详解的更多相关文章

  1. python标准库介绍——27 random 模块详解

    ==random 模块== "Anyone who considers arithmetical methods of producing random digits is, of cour ...

  2. python标准库介绍——12 time 模块详解

    ==time 模块== ``time`` 模块提供了一些处理日期和一天内时间的函数. 它是建立在 C 运行时库的简单封装. 给定的日期和时间可以被表示为浮点型(从参考时间, 通常是 1970.1.1 ...

  3. python标准库介绍——10 sys 模块详解

    ==sys 模块== ``sys`` 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. === 处理命令行参数=== 在解释器启动后, ``argv`` 列表包含了传递给脚本的所有 ...

  4. python标准库介绍——30 code 模块详解

    ==code 模块== ``code`` 模块提供了一些用于模拟标准交互解释器行为的函数. ``compile_command`` 与内建 ``compile`` 函数行为相似, 但它会通过测试来保证 ...

  5. python标准库介绍——18 StringIO 模块详解

    ==StringIO 模块== [Example 2-8 #eg-2-8] 展示了 ``StringIO`` 模块的使用. 它实现了一个工作在内存的文件对象 (内存文件). 在大多需要标准文件对象的地 ...

  6. python标准库介绍——8 operator 模块详解

    ==operator 模块== ``operator`` 模块为 Python 提供了一个 "功能性" 的标准操作符接口. 当使用 ``map`` 以及 ``filter`` 一类 ...

  7. python标准库介绍——36 popen2 模块详解

    ==popen2 模块== ``popen2`` 模块允许你执行外部命令, 并通过流来分别访问它的 ``stdin`` 和 ``stdout`` ( 可能还有 ``stderr`` ). 在 pyth ...

  8. python标准库介绍——23 UserString 模块详解

    ==UserString 模块== (2.0 新增) ``UserString`` 模块包含两个类, //UserString// 和 //MutableString// . 前者是对标准字符串类型的 ...

  9. python标准库介绍——22 UserList 模块详解

    ==UserList 模块== ``UserList`` 模块包含了一个可继承的列表类 (事实上是对内建列表类型的 Python 封装). 在 [Example 2-16 #eg-2-16] 中, / ...

随机推荐

  1. Visual SVN的安装

    作为一个程序开发人员,就算自己一个人写程序,也应该有一个SVN版本控制系统,以便对开发代码进行有效的管理.今天我就介绍一个在Windows环境下简单快速搭建SVN服务器的方法. 通常的SVN服务器是搭 ...

  2. 从头认识Spring-1.14 SpEl表达式(1)-简单介绍与嵌入值

    这一章节我们来讨论一下SpEl表达式的简单介绍与嵌入值. 1.SpEl表达式简单介绍 Spring Excpression Language (SpEL)语言支持在执行时操作和查询对象 事实上就是在执 ...

  3. 算法笔记_216:第六届蓝桥杯软件类校赛部分真题(Java语言C组)

    目录 1 题目一 2 题目二 3 题目三 4 题目四 5 题目五 前言:以下代码仅供参考,若有错误欢迎指正哦~ 1 题目一 二项式的系数规律,我国数学家很早就发现了. 如[图1.png],我国南宋数学 ...

  4. JavaWeb项目异常管理之log4j的使用教程

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6399191.html 在项目中的应用见: https://github.com/ygj0930/CoupleS ...

  5. Oracle Data Integrator 12c----简单CDC(Simple CDC)

    Simple CDC最简单的一种 CDC.在这里,每一张 CDC 的表的变化都是独立捕获的,不需要考虑多张存在主外键引用关系的表之间的数据一致性. 1 环境准备 源表:ODI_SRC.DEPT 目标表 ...

  6. PHP中使用ActiveMQ实现消息队列

    前面我们已经学了怎样部署ActiveMQ. 我们知道通过ActiveMQ的一个管理后台能够查看任务队列. 今天 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQ ...

  7. 【DB2】SQL优化

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAA

  8. 【JMeter】初识JMeter(1)

    一.JMeter介绍 JMeter是一款开源桌面应用软件,可以用来模拟用户负载来完成性能测试工作.JMeter的功能在版本升级的过程中已经十分强大,现在多数互联网公司都在使用JMeter来完成产品或者 ...

  9. Kinect2.0获取关节姿态(Joint Orientation)

    Bones Hierarchy 骨骼层次结构从SpineBase作为根节点开始,一直延伸到肢体末端(头.指尖.脚): 层级结构如下图所示: 通过IBody::GetJointOrientations函 ...

  10. nginx搭建httpsserver

    HTTPS简单介绍 HTTPS(Hypertext Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单来讲就是HTTP的安全版. ...