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

yipeiwu_com5年前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读写Redis数据库操作示例

使用Python如何操作Redis呢?下面用实例来说明用Python读写Redis数据库。比如,我们插入一条数据,如下:复制代码 代码如下:import redisclass Datab...

python统计cpu利用率的方法

本文实例讲述了python统计cpu利用率的方法。分享给大家供大家参考。具体实现方法如下: #-*-coding=utf-8-*- import win32pdh import ti...

Selenium鼠标与键盘事件常用操作方法示例

Selenium鼠标与键盘事件常用操作方法示例

本文实例讲述了Selenium鼠标与键盘事件常用操作方法。分享给大家供大家参考,具体如下: Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就...

对Python中class和instance以及self的用法详解

一. Python 的类和实例 在面向对象中,最重要的概念就是类(class)和实例(instance),类是抽象的模板,而实例是根据类创建出来的一个个具体的 “对象”。 就好比,学生是...

python判断文件是否存在,不存在就创建一个的实例

如下所示: try: f =open("D:/1.txt",'r') f.close() except IOError: f = open("D:/1.txt",'w')...