Python中使用gzip模块压缩文件的简单教程
2015-04-08 09:47
1111 查看
压缩数据创建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程序中用csv模块来操作csv文件的基本使用教程
- Python下使用tarfile模块来实现文件归档压缩与解压
- 使用Python标准库中的wave模块绘制乐谱的简单教程
- 飘逸的python - 简明gzip模块压缩教程
- 飘逸的python - 简明gzip模块压缩教程
- 重温python之OS模块的简单使用5:os.chown()更改文件所有者
- 飘逸的python - 简明gzip模块压缩教程
- Python程序中用csv模块来操作csv文件的基本使用教程
- 重温python之OS模块的简单使用4:os.chmod() 更改文件或目录的权限
- 在Python下使用gzip压缩文件
- 利用python中的gzip模块压缩和解压数据流和文件
- 在Python中使用zlib模块进行数据压缩的教程
- 在Python中使用zlib模块进行数据压缩的教程
- Python下使用tarfile模块来实现文件归档压缩与解压
- Python下使用tarfile模块来实现文件归档压缩与解压
- Python_使用csv模块解析csv文件
- python处理图片之PIL模块简单使用
- [Python学习] Logging模块的简单使用
- PYthon模块使用教程
- python的md5模块使用非常简单