码迷,mamicode.com
首页 > 编程语言 > 详细

python使用zlib实现压缩与解压字符串

时间:2016-04-30 18:17:08      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:

命令

字符串:使用zlib.compress可以压缩字符串。使用zlib.decompress可以解压字符串。

数据流:压缩:compressobj,解压:decompressobj

案例

>>> import zlib
>>> s = slfsjdalfkasflkkdkaleeeeeeeeeeeeeeeeeeeeeeeeeeeelaaalkllfksaklfasdll  kkkkkk123
>>> zlib_s = zlib.compress(s)
>>> zlib_s
x\x9c}\xca\xb1\r\xc0 \x10\x04\xc1Vh\xc1\xb8\xa2\x93\x9e\x0f|\x9b]\xff\x92\x11\x050\xf1\x84\xceW\xa2\xad4vY\xac\x0b$a\xf6\x8fL+\x05c\xf8x\xe6\xfb\x03\xf7\x97\x1e\xd1

>>> print tlen(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name tlen is not defined
>>> print len(s)
79
>>> print len(zlib_s)
55
>>> ss = zlib.decompress(zlib_s) >>> ss slfsjdalfkasflkkdkaleeeeeeeeeeeeeeeeeeeeeeeeeeeelaaalkllfksaklfasdll kkkkkk123

压缩与解压缩文件

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__":
    infile = "1.txt"
    dst = "1.zlib.txt"
    compress(infile, dst)
    
    infile = "1.zlib.txt"
    dst = "2.txt"
    decompress(infile, dst)
    print "done~"

注:compressobj返回一个压缩对象,用来压缩不能一下子读入内存的数据流。 level 从9到-1表示压缩等级,其中1最快但压缩度最小,9最慢但压缩度最大,0不压缩,默认是-1大约相当于与等级6,是一个压缩速度和压缩度适中的level。

python使用zlib实现压缩与解压字符串

标签:

原文地址:http://www.cnblogs.com/kaituorensheng/p/5448761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!