Python中使用gzip模块压缩文件的简单教程
压缩数据创建gzip文件
先看一个略麻烦的做法
importStringIO,gzip content='Lifeisshort.Iusepython' 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语句
importgzip
withopen("/path/to/file",'rb')asplain_file:
withgzip.open("/path/to/file.gz",'wb')aszip_file:
zip_file.writelines(plain_file)
如果不考虑跨平台,只在linux平台,下面这种方式更直接
fromsubprocessimportcheck_call
check_call('gzip/path/to/file',shell=True)
热门推荐
4 狗狗请人训练
5 训练狗狗迎宾
6 训练狗狗解放
7 抬头训练狗狗
10 训练狗狗的基本动作
11 两个月狗狗怎么训练大小便
12 教狗狗训练
13 记叙文训练狗狗
14 潮州训练狗狗
15 训练狗狗叫的方法
16 猫训练狗狗
17 狗狗训练如厕
18 狗狗来训练