Python中使用gzip模块压缩文件的简单教程
2019/7/13 21:26:25
本文主要是介绍Python中使用gzip模块压缩文件的简单教程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
压缩数据创建gzip文件
先看一个略麻烦的做法
import StringIO,gzip content = 'Life is short.I use python' zbuf = StringIO.StringIO() zfile = gzip.GzipFile(mode='wb', compresslevel=9, fileobj=zbuf) zfile.write(content) zfile.close()
但其实有个快捷的封装,不用用到StringIO模块
f = gzip.open('file.gz', 'wb') f.write(content) f.close()
压缩已经存在的文件
python2.7后,可以用with语句
import gzip with open("/path/to/file", 'rb') as plain_file: with gzip.open("/path/to/file.gz", 'wb') as zip_file: zip_file.writelines(plain_file)
如果不考虑跨平台,只在linux平台,下面这种方式更直接
from subprocess import check_call check_call('gzip /path/to/file',shell=True)
这篇关于Python中使用gzip模块压缩文件的简单教程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python