python通过zlib实现压缩与解压字符串的方法
2014-11-19 11:15
921 查看
使用zlib.compress可以压缩字符串。使用zlib.decompress可以解压字符串。如下
import zlib
s = "hello word, 00000000000000000000000000000000"
print len(s)
c = zlib.compress(s)
print len(c)
d = zlib.decompress(c)
print d
示范代码2:
复制代码 代码如下: import zlib
message = 'witch which has which witches wrist watch'
compressed = zlib.compress(message)
decompressed = zlib.decompress(compressed)
print 'original:', repr(message)
print 'compressed:', repr(compressed)
print 'decompressed:', repr(decompressed) #输出original: 'witch which has which witches wrist watch'
compressed: 'xx9c+xcf,IxceP(xcfxc8x04x92x19x89xc5PV9H4x15xc8+xca,.Q(Ox04xf2x00D?x0fx89'
decompressed: 'witch which has which witches wrist watch'
如果我们要对字符串进行解压可以使用zlib.compressobj和zlib.decompressobj对文件进行压缩解压
复制代码 代码如下: 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())
希望本文所述对大家的Python程序设计有所帮助。
您可能感兴趣的文章:
相关文章推荐
- python通过zlib实现压缩与解压字符串的方法
- python用模块zlib压缩与解压字符串和文件的方法
- python使用zlib实现压缩与解压字符串
- python用模块zlib压缩与解压字符串和文件的方法
- python用模块zlib压缩与解压字符串和文件的方法
- Python实现多级目录压缩与解压文件的方法
- Python实现压缩与解压gzip大文件的方法
- Python zlib()实现压缩和解压
- python通过zlib实现压缩文件内容(str),和解压缩还原文件内容
- Python通过解析网页实现看报程序的方法
- python实现忽略大小写对字符串列表排序的方法
- python实现从字符串中找出字符1的位置以及个数的方法
- [转]PHP通过zlib扩展实现GZIP压缩输出
- Python中实现字符串类型与字典类型相互转换的方法
- python实现在pickling的时候压缩的方法
- python中实现字符串反转的几种方法
- python实现从字符串中找出字符1的位置以及个数的方法
- Python通过解析网页实现看报程序的方法
- python实现在pickling的时候压缩的方法
- Python下使用tarfile模块来实现文件归档压缩与解压