zipfile --- 處理 ZIP 封存檔案¶
原始碼:Lib/zipfile/
ZIP 檔案格式是一種常見的封存 (archive) 與壓縮標準。本模組提供了建立、讀取、寫入、附加與列出 ZIP 檔案的工具。任何對本模組的進階使用都將需要對 PKZIP Application Note 中定義的格式有所理解。
本模組不處理多組件 (multipart) ZIP 檔案。它可以處理使用 ZIP64 擴充(即大於 4 GiB 的 ZIP 檔案)的 ZIP 檔案。它支援解密 ZIP 封存檔案中的加密檔案,但目前無法建立加密檔案。解密速度極慢,因為它是在原生 Python 中實作,而不是 C。
Handling compressed archives requires optional modules
such as zlib, bz2, lzma, and compression.zstd.
If any of them are missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see 可選模組的需求.
本模組定義了以下項目:
- exception zipfile.BadZipFile¶
對於損壞的 ZIP 檔案所引發的錯誤。
在 3.2 版被加入.
- exception zipfile.BadZipfile¶
BadZipFile的別名,為了與舊版 Python 相容。在 3.2 版之後被棄用.
- exception zipfile.LargeZipFile¶
當 ZIP 檔案需要 ZIP64 功能但該功能未被啟用時所引發的錯誤。
- class zipfile.ZipFile
用於讀取和寫入 ZIP 檔案的類別。有關建構函式的詳細資訊,請參閱 ZipFile 物件 章節。
- class zipfile.Path
實作了
pathlib.Path所提供介面子集的類別,包括完整的importlib.resources.abc.Traversable介面。在 3.8 版被加入.
- class zipfile.PyZipFile
用於建立包含 Python 函式庫的 ZIP 封存檔案的類別。
- class zipfile.ZipInfo(filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))¶
用於表示封存檔案中成員資訊的類別。此類別的實例由
ZipFile物件的getinfo()和infolist()方法回傳。大多數zipfile模組的使用者不需要建立這些實例,而只需使用本模組所建立的。filename 應為封存成員的完整名稱,而 date_time 應為一個包含六個欄位的元組,用以描述檔案的最後修改時間;這些欄位在 ZipInfo 物件 章節中有所描述。在 3.13 版的變更: 新增了一個公開的
compress_level屬性,以公開先前受保護的_compresslevel。為了向後相容,舊的受保護名稱仍可作為一個特性繼續運作。- _for_archive(archive)¶
Resolve the date_time, compression attributes, and external attributes to suitable defaults as used by
ZipFile.writestr().Returns self for chaining.
在 3.14 版被加入.
- zipfile.is_zipfile(filename)¶
如果 filename 根據其魔術數字(magic number)是一個有效的 ZIP 檔案,則回傳
True,否則回傳False。filename 也可以是一個檔案或類檔案物件。在 3.1 版的變更: 支援檔案和類檔案物件。
- zipfile.ZIP_STORED¶
用於未壓縮封存成員的數值常數。
- zipfile.ZIP_ZSTANDARD¶
用於 Zstandard 壓縮方法的數值常數。這需要
compression.zstd模組。備註
In APPNOTE 6.3.7, the method ID
20was assigned to Zstandard compression. This was changed in APPNOTE 6.3.8 to method ID93to avoid conflicts, with method ID20being deprecated. For compatibility, thezipfilemodule reads both method IDs but will only write data with method ID93.在 3.14 版被加入.
備註
ZIP 檔案格式規範自 2001 年起已包含對 bzip2 壓縮的支援、自 2006 年起支援 LZMA 壓縮、自 2020 年起支援 Zstandard 壓縮。然而某些工具(包括舊版的 Python)不支援這些壓縮方法,可能會完全拒絕處理該 ZIP 檔案,或無法解壓縮個別檔案。
也參考
- PKZIP Application Note
由 Phil Katz(該格式與所用演算法的創造者)所撰寫的關於 ZIP 檔案格式的文件。
- Info-ZIP 首頁
關於 Info-ZIP 專案的 ZIP 封存程式和開發函式庫的資訊。
ZipFile 物件¶
- class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True, metadata_encoding=None)¶
開啟一個 ZIP 檔案,其中 file 可以是一個檔案的路徑(一個字串)、一個類檔案物件或一個 path-like object。
mode 參數應為
'r'來讀取一個現有檔案、'w'來清空並寫入一個新檔案、'a'來附加到一個現有檔案,或'x'來獨佔性地建立並寫入一個新檔案。如果 mode 為'x'且 file 指向一個現有檔案,將會引發FileExistsError。如果 mode 為'a'且 file 指向一個現有的 ZIP 檔案,則會將額外的檔案加入其中。如果 file 並非指向一個 ZIP 檔案,則一個新的 ZIP 封存檔案會被附加到該檔案之後。這適用於將一個 ZIP 封存檔案附加到另一個檔案(例如python.exe)。如果 mode 為'a'且檔案完全不存在,它會被建立。如果 mode 為