手机
当前位置:查字典教程网 >脚本专栏 >python >Python中使用gzip模块压缩文件的简单教程
Python中使用gzip模块压缩文件的简单教程
摘要:压缩数据创建gzip文件先看一个略麻烦的做法importStringIO,gzipcontent='Lifeisshort.Iusepyth...

压缩数据创建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中使用gzip模块压缩文件的简单教程】相关文章:

Python Web框架Pylons中使用MongoDB的例子

Python tempfile模块学习笔记(临时文件)

python使用rsa加密算法模块模拟新浪微博登录

Python中删除文件的程序代码

Python中apply函数的用法实例教程

python使用urllib模块开发的多线程豆瓣小站mp3下载器

在Python中使用异步Socket编程性能测试

Python使用PyGreSQL操作PostgreSQL数据库教程

Python中使用urllib2防止302跳转的代码例子

python使用内存zipfile对象在内存中打包文件示例

精品推荐
分类导航