python用模块zlib压缩与解压字符串和文件的方法
2016-12-16 00:00
741 查看
python中zlib模块是用来压缩或者解压缩数据,以便保存和传输。它是其他压缩工具的基础。下面来一起看看python用模块zlib压缩与解压字符串和文件的方法。话不多说,直接来看示例代码。
例子1:压缩与解压字符串
结果
例子2:压缩与解压文件
结果
生成文件
问题――处理对象过大异常
总结
以上就是关于python模块zlib压缩与解压的全部内容,希望本文的内容对大家学习或者使用python能有一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
在Python中使用zlib模块进行数据压缩的教程
Python压缩和解压缩zip文件
Python中使用tarfile压缩、解压tar归档文件示例
Python压缩解压缩zip文件及破解zip文件密码的方法
使用Python读写及压缩和解压缩文件的示例
使用Python压缩和解压缩zip文件的教程
Python实现压缩与解压gzip大文件的方法
例子1:压缩与解压字符串
import zlib message = 'abcd1234' compressed = zlib.compress(message) decompressed = zlib.decompress(compressed) print 'original:', repr(message) print 'compressed:', repr(compressed) print 'decompressed:', repr(decompressed)
结果
original: 'abcd1234' compressed: 'x\x9cKLJN1426\x01\x00\x0b\xf8\x02U' decompressed: 'abcd1234'
例子2:压缩与解压文件
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')
结果
生成文件
out_decompress.txt out.txt
问题――处理对象过大异常
>>> import zlib >>> a = '123' >>> b = zlib.compress(a) >>> b 'x\x9c342\x06\x00\x01-\x00\x97' >>> a = 'a' * 1024 * 1024 * 1024 * 10 >>> b = zlib.compress(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: size does not fit in an int
总结
以上就是关于python模块zlib压缩与解压的全部内容,希望本文的内容对大家学习或者使用python能有一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
您可能感兴趣的文章:
python通过zlib实现压缩与解压字符串的方法在Python中使用zlib模块进行数据压缩的教程
Python压缩和解压缩zip文件
Python中使用tarfile压缩、解压tar归档文件示例
Python压缩解压缩zip文件及破解zip文件密码的方法
使用Python读写及压缩和解压缩文件的示例
使用Python压缩和解压缩zip文件的教程
Python实现压缩与解压gzip大文件的方法
相关文章推荐
- python用模块zlib压缩与解压字符串和文件的方法
- python用模块zlib压缩与解压字符串和文件的方法
- python通过zlib实现压缩与解压字符串的方法
- python通过zlib实现压缩与解压字符串的方法
- python使用zlib实现压缩与解压字符串
- python 模块zlib 压缩与解压
- python中压缩和解压文件的方法
- 利用python中的gzip模块压缩和解压数据流和文件
- Python实现压缩与解压gzip大文件的方法
- Python实现多级目录压缩与解压文件的方法
- 4000 python中的zlib模块提供了压缩和解压缩的方法
- Python下使用tarfile模块来实现文件归档压缩与解压
- Python下使用tarfile模块来实现文件归档压缩与解压
- Python下使用tarfile模块来实现文件归档压缩与解压
- C++ zlib 压缩解压文件
- linux下tar gz bz2 tgz z等众多压缩文件的解压方法
- linux下tar gz bz2 tgz z等众多压缩文件的解压方法
- 使用ZLIB生成DLL文件,并进行有中文的ZIP文件压缩与解压操作!支持目录压与解!
- 解压RAR时出现“不可预料的压缩文件末端”的解决方法
- Linux/Unix下各种压缩文件的压缩/解压方法