模块zlib 压缩与解压

模块zlib用来解压和压缩字符串或者文件,能够自动识别压缩格式来自动解压。

字符串的解压与字符串:

1
2
3
4
5
6
7
8
import zlib
message = 'abcd1234'
compressed = zlib.compress(message)
decompressed = zlib.decompress(compressed)

print 'original:', repr(message)
print 'compressed:', repr(compressed)
print 'decompressed:', repr(decompressed)

结果是:

1
2
3
original: 'abcd1234'
compressed: 'x\x9cKLJN1426\x01\x00\x0b\xf8\x02U'
decompressed: 'abcd1234'

文件的压缩和解压文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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__":
compress('in.txt', 'out.txt')
decompress('out.txt', 'out_decompress.txt')

生成的文件:

1
out_decompress.txt  out.txt

PS:zlib.compress用于压缩流数据。参数string指定了要压缩的数据流,参数level指定压缩的级别,它的取值范围是1到9。压缩速度与压缩率成反比,1表示压缩速度最快,而压缩率最低,而9则表示压缩速度最慢但压缩率最高

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×