发布于 2015-11-09 12:58:32 | 228 次阅读 | 评论: 0 | 来源: 网友投递
Python编程语言
Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。
压缩数据创建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)