源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-12-12 10:18 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python中使用gzip模块压缩文件的简单教程
[b]压缩数据创建gzip文件 [/b]先看一个略麻烦的做法  
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()
[b]压缩已经存在的文件 [/b]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)
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部