壓縮數據創建gzip文件
先看一個略麻煩的做法
1
2
3
4
5
6
|
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模塊
1
2
3
|
f = gzip. open ( 'file.gz' , 'wb' ) f.write(content) f.close() |
壓縮已經存在的文件
python2.7后,可以用with語句
1
2
3
4
|
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平臺,下面這種方式更直接
1
2
|
from subprocess import check_call check_call( 'gzip /path/to/file' ,shell = True ) |