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交互式图形编程的第二部分代码,供大家参考,具体内容如下 #!/usr/bin/env python3 # -*- coding: utf-8 -*-...

django 自定义过滤器(filter)处理较为复杂的变量方法

简述:django 在views中有数据需要通过字典(dict)的方式传递给template,该字典中又包含了字典,而且字典中的键值还是一个对象,在template中处理传递过来的数据的...

python3中pip3安装出错,找不到SSL的解决方式

最近在Ubuntu16.04上安装Python3.6之后,使用pip命令出现了问题,提示说找不到ssl模块,出现错误如下: pip is configured with locati...

用Pycharm实现鼠标滚轮控制字体大小的方法

用Pycharm实现鼠标滚轮控制字体大小的方法

一、pycharm字体放大的设置 File —> setting —> Keymap —>在搜寻框中输入:increase —> Increase Font Si...

python通过colorama模块在控制台输出彩色文字的方法

本文实例讲述了python通过colorama模块在控制台输出彩色文字的方法。分享给大家供大家参考。具体分析如下: colorama是一个python专门用来在控制台、命令行输出彩色文字...