码迷,mamicode.com
首页 > 编程语言 > 详细

python gzip 压缩文件

时间:2015-08-17 00:58:29      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

压缩数据创建gzip文件
先看一个略麻烦的做法
 

1
2
3
4
5
6
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模块
 

1
2
3
f = gzip.open(‘file.gz‘, ‘wb‘)
f.write(content)
f.close()

压缩已经存在的文件
python2.7后,可以用with语句
 

1
2
3
4
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平台,下面这种方式更直接
 

1
2
from subprocess import check_call
check_call(‘gzip /path/to/file‘,shell=True)

python gzip 压缩文件

标签:

原文地址:http://www.cnblogs.com/x113/p/4735353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!