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

yipeiwu_com6年前Python基础

压缩数据创建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中的内置函数getattr()介绍及示例

在python的官方文档中:getattr()的解释如下: getattr(object, name[, default]) Return the value of the nam...

wxPython中文教程入门实例

wxPython中文教程入门实例 wx.Window 是一个基类,许多构件从它继承。包括 wx.Frame 构件。可以在所有的子类中使用 wx.Window 的方法。 wxPython的...

Python中使用items()方法返回字典元素对的教程

 items()方法返回字典的(键,值)元组对的列表 语法 以下是items()方法的语法: dict.items() 参数    ...

Django模板Templates使用方法详解

Django模板Templates使用方法详解

一、django的模板: 在settings.py的文件中可以看到并设置这个模板。 1.直接映射: 通过建立的文件夹(templates)和文件(html)来映射。 <!D...

python安装Scrapy图文教程

python安装Scrapy图文教程

安装方法 pip install Scrapy 如果顺利的话不用管直接一路下来就OK 验证是否安装成功 安装成功 不顺利的情况 1)lxml安装不成功 使用whl进行安装,不过需要先...