python通过zlib实现压缩与解压字符串的方法
本文实例讲述了python通过zlib实现压缩与解压字符串的方法。分享给大家供大家参考。具体实现方法如下:
使用zlib.compress可以压缩字符串。使用zlib.decompress可以解压字符串。如下
#coding=utf-8 importzlib s="helloword,00000000000000000000000000000000" printlen(s) c=zlib.compress(s) printlen(c) d= zlib.decompress(c) printd
示范代码2:
importzlib message='witchwhichhaswhichwitcheswristwatch' compressed=zlib.compress(message) decompressed=zlib.decompress(compressed) print'original:',repr(message) print'compressed:',repr(compressed) print'decompressed:',repr(decompressed)#输出original:'witchwhichhaswhichwitcheswristwatch' compressed:'xx9c+xcf,IxceP(xcfxc8x04x92x19x89xc5PV9H4x15xc8+xca,.Q(Ox04xf2x00D?x0fx89' decompressed:'witchwhichhaswhichwitcheswristwatch'
如果我们要对字符串进行解压可以使用zlib.compressobj和zlib.decompressobj对文件进行压缩解压
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())
希望本文所述对大家的Python程序设计有所帮助。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短