壓縮數(shù)據(jù)創(chuàng)建gzip文件
先看一個略麻煩的做法
import StringIO,gzipcontent = 'Life is short.I use python'zbuf = StringIO.StringIO()zfile = gzip.GzipFile(mode='wb', compresslevel=9, fileobj=zbuf)zfile.write(content)zfile.close()
但其實(shí)有個快捷的封裝,不用用到StringIO模塊
f = gzip.open('file.gz', 'wb')f.write(content)f.close()
壓縮已經(jīng)存在的文件
python2.7后,可以用with語句
import gzipwith 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_callcheck_call('gzip /path/to/file',shell=True)
新聞熱點(diǎn)
疑難解答
圖片精選