• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-09) 11次浏览 已收录 0个评论

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

import StringIO,gzipcon<b style="color:transparent">本文来源gao@!dai!ma.com搞$$代^@码网*</b>tent = '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)

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python中使用gzip模块压缩文件的简单教程
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

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

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