python gzip模塊壓縮簡明教程
壓縮數據創建gzip文件
先看一個略麻煩的做法
但其實有個快捷的封裝,不用用到StringIO模塊
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)
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!