gzip --- gzip 壓縮與解壓縮

本模組允許使用 gzip 檔案格式所採用的 DEFLATE 演算法 對二進位資料進行壓縮與解壓縮。它提供一次性的 compress()decompress() 輔助函式,以及包裝底層檔案或串流物件的串流式 GzipFile

備註

請優先使用 deflate.DeflateIO 而非本模組中的函式,因為它提供壓縮與解壓縮的串流式介面,在讀寫壓縮資料至檔案、socket 或串流時更為方便且更節省記憶體。

可用性:

  • 本模組預設並未包含於 OpenMV Cam 中,因為它重複了 deflate 模組已提供的功能。

  • 可從 micropython-lib原始碼)安裝副本(或凍結進自訂韌體)。詳情請參閱 套件管理。本文件描述的即為該模組。

  • 僅當內建的 deflate 模組提供壓縮功能時,壓縮才可用——亦即在以 STM32 為基礎的 OpenMV Cam 上不可用(參見上方的可用性說明)。

函式

gzip.open(filename: str, mode: str, /) GzipFile

包裝內建的 open(),回傳一個 GzipFile 實例。

gzip.decompress(data: bytes, /) bytes

data 解壓縮為 bytes 物件。

gzip.compress(data: bytes, /) bytes

data 壓縮為 bytes 物件。

類別

class gzip.GzipFile(*, fileobj, mode: str)

此類別可用來包裝 fileobj,後者為任何 類串流 物件,例如檔案、socket 或串流(包含 io.BytesIO)。它本身即為一個串流,並實作標準的 read/readinto/write/close 方法。

mode 引數為 "rb" 時,從 GzipFile 實例讀取會解壓縮底層串流中的資料並回傳解壓縮後的資料。

若啟用壓縮支援,則 mode 引數可設定為 "wb",寫入 GzipFile 實例的資料會被壓縮並寫入底層串流。

GzipFile 類別預設會使用 gzip 檔案格式讀寫資料,包含含有校驗和的標頭與標尾,以及 512 位元組的視窗大小。

filecompresslevelmtime 引數不受支援。fileobjmode 必須一律以關鍵字引數指定。

範例

gzip.GzipFile 的典型使用情境是從儲存裝置讀取或寫入壓縮檔:

import gzip

# Reading:
with open("data.gz", "rb") as f:
    with gzip.GzipFile(fileobj=f, mode="rb") as g:
        # Use g.read(), g.readinto(), etc.

 # Same, but using gzip.open:
with gzip.open("data.gz", "rb") as f:
     # Use f.read(), f.readinto(), etc.

# Writing:
with open("data.gz", "wb") as f:
    with gzip.GzipFile(fileobj=f, mode="wb") as g:
        # Use g.write(...) etc

# Same, but using gzip.open:
with gzip.open("data.gz", "wb") as f:
    # Use f.write(...) etc

# Write a dictionary as JSON in gzip format, with a
# small (64 byte) window size.
config = { ... }
with gzip.open("config.gz", "wb") as f:
    json.dump(config, f)

關於處理 gzip 來源與選擇視窗大小的指引,請參閱 deflate 文件末尾 的說明。