Python中使用gzip模块压缩文件的简单教程_python教程-查字典教程网
Python中使用gzip模块压缩文件的简单教程
Python中使用gzip模块压缩文件的简单教程
发布时间:2016-12-28 来源:查字典编辑
摘要:压缩数据创建gzip文件先看一个略麻烦的做法importStringIO,gzipcontent='Lifeisshort.Iusepyth...

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

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新python学习
    热门python学习
    脚本专栏子分类