脚本专栏 
首页 > 脚本专栏 > 浏览文章

Python中使用gzip模块压缩文件的简单教程

(编辑:jimmy 日期: 2024/5/20 浏览:3 次 )

压缩数据创建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)

上一篇:Windows下用py2exe将Python程序打包成exe程序的教程
下一篇:Python bsddb模块操作Berkeley DB数据库介绍
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网