秦皇岛seo博主拥有多年seo,网络营销推广经验,曾服务于多家中大型企业,众多成功案例,可为您提供专业的网站seo,网络营销推广,网站建设等服务。点击这里给我发消息

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

编程代码 秦皇岛seo 680℃ 0评论

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

import StringIO,gzipcontent = '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 gzipwith 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_callcheck_call('gzip /path/to/file',shell=True)

转载请注明:老街华纳公司开户-MD62333 » Python中使用gzip模块压缩文件的简单教程

喜欢 (0)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址