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