命令
字符串:使用zlib.compress可以压缩字符串。使用zlib.decompress可以解压字符串。
数据流:压缩:compressobj,解压:decompressobj
案例
>>> import zlib >>> s = 'slfsjdalfkasflkkdkaleeeeeeeeeeeeeeeeeeeeeeeeeeeelaaalkllfksaklfasdll kkkkkk123' >>> zlib_s = zlib.compress(s) >>> zlib_s 'xx9c}xcaxb1 xc0 x10x04xc1Vhxc1xb8xa2x93x9ex0f|x9b]xffx92x11x050xf1x84xceWxa2xad4vYxacx0b$axf6x8fL+x05cxf8xxe6xfbx03xf7x97x1exd1' >>> 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。