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画一颗心的方法示例

利用python画一颗心的方法示例

前言 Python一般使用Matplotlib制作统计图形,用它自己的说法是‘让简单的事情简单,让复杂的事情变得可能'。用它可以制作折线图,直方图,条形图,散点图,饼图,谱图等等你能想到...

python算法表示概念扫盲教程

python算法表示概念扫盲教程

本文为大家讲解了python算法表示概念,供大家参考,具体内容如下 常数阶O(1) 常数又称定数,是指一个数值不变的常量,与之相反的是变量 为什么下面算法的时间复杂度不是O(3),而是O...

python turtle 绘制太极图的实例

python turtle 绘制太极图的实例

效果如下所示: # -*- coding: utf-8 -*- import turtle # 绘制太极图函数 def draw_TJT(R):    ...

Python实现的多线程同步与互斥锁功能示例

Python实现的多线程同步与互斥锁功能示例

本文实例讲述了Python实现的多线程同步与互斥锁功能。分享给大家供大家参考,具体如下: #! /usr/bin/env python #coding=utf-8 import th...

使用Python压缩和解压缩zip文件的教程

python 的 zipfile 提供了非常便捷的方法来压缩和解压 zip 文件。 例如,在py脚本所在目录中,有如下文件: 复制代码 代码如下:readability/readabil...