python 讀寫壓縮檔案
阿新 • • 發佈:2018-12-14
gzip
和 bz2
模組可以很容易的處理這些檔案。 兩個模組都為 open()
函式提供了另外的實現來解決這個問題。
比如,為了以文字形式讀取壓縮檔案,可以這樣做:
# gzip compression import gzip with gzip.open('somefile.gz', 'rt') as f: text = f.read() # bz2 compression import bz2 with bz2.open('somefile.bz2', 'rt') as f: text= f.read()
類似的,為了寫入壓縮資料,可以這樣做:
# gzip compression import gzip with gzip.open('somefile.gz', 'wt') as f: f.write(text) # bz2 compression import bz2 with bz2.open('somefile.bz2', 'wt') as f: f.write(text)
如上,所有的I/O操作都使用文字模式並執行Unicode的編碼/解碼。
類似的,如果你想操作二進位制資料,使用 rb
或者 wb
檔案模式即可。