python使用zlib实现压缩与解压字符串
命令
字符串:使用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。