Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2301361
  • 博文数量: 321
  • 博客积分: 3440
  • 博客等级: 中校
  • 技术积分: 2992
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-24 09:08
个人简介

我就在这里

文章分类

全部博文(321)

文章存档

2015年(9)

2014年(84)

2013年(101)

2012年(25)

2011年(29)

2010年(21)

2009年(6)

2008年(23)

2007年(23)

分类: Python/Ruby

2013-01-10 21:49:54

A:如何使用zlib模块来进行压缩解压了? 
Q:

1.使用zlib.compress可以压缩字符串。使用zlib.decompress可以解压字符串。 
压缩解压字符串示范代码:

import zlib
message = 'witch which has which witches wrist watch'
compressed = zlib.compress(message) 
decompressed = zlib.decompress(compressed) 
print 'original:', repr(message) 
print 'compressed:', repr(compressed) 
print 'decompressed:', repr(decompressed) 输出original: 'witch which has which witches wrist watch'
compressed: 'x\x9c+\xcf,I\xceP(\xcf\xc8\x04\x92\x19\x89\xc5PV9H4\x15\xc8+\xca,.Q(O\x04\xf2\x00D?\x0f\x89'
decompressed: 'witch which has which witches wrist watch'

2.使用zlib.compressobj和zlib.decompressobj比较适合用于对文件进行压缩解压。 
以下定义的两个函数可以做为使用zlib.compressobj和zlib.decompressobj对文件进行压缩解压的例子:

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())
阅读(3352) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~