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类:class创建、数据方法属性及访问控制详解

python类:class创建、数据方法属性及访问控制详解

在Python中,可以通过class关键字定义自己的类,然后通过自定义的类对象类创建实例对象。 python中创建类 创建一个Student的类,并且实现了这个类的初始化函数”__ini...

Python操作Excel插入删除行的方法

1. 前言 由于近期有任务需要,要写一个能够处理Excel的脚本,实现的功能是,在A表格上其中一列,对字符串进行分组和排序,然后根据排序好的A表格以固定格式自动填写到B表格上。 开始写脚...

Windows下python3.6.4安装教程

Windows下python3.6.4安装教程

Windows下python3.6.4安装教程的详细过程,供大家参考,具体内容如下 步骤: 下包—>安装—->添加环境变量—–>测试 1、下包 Python安装包下载...

python中matplotlib条件背景颜色的实现

如何根据图表中没有的变量更改折线图的背景颜色?例如,如果我有以下数据帧: import numpy as np import pandas as pd dates = pd.dat...

实例讲解Python编程中@property装饰器的用法

取值和赋值 class Actress(): def __init__(self): self.name = 'TianXin' self.age = 5...