在 Python 中開啟一個 Zip 檔案而不解壓它
Najwa Riyaz
2023年10月10日
Python
Python File
-
在 Python 中使用
zipfile.ZipFile()函式開啟一個 Zip 檔案,而無需臨時解壓縮它 -
在 Python 中使用
ZipFile.open()函式開啟一個 Zip 檔案,而無需臨時提取它
本文介紹瞭如何在 Python 軟體中開啟 zip 檔案而無需臨時解壓。要開啟 zip 檔案而不用 Python 臨時解壓縮它,請使用 zipfile Python 庫。
為此,匯入 zipfile 標準庫。然後,使用以下任一功能。
- 在讀取模式下使用
zipfile.ZipFile()函式。 - 在讀取模式下使用
ZipFile.open()函式。
在我們開始之前,請準備好 zip 檔案。請按照以下步驟操作。
-
準備一個名為
mail.txt的文字檔案,其中包含一些內容:This is from mail.txt -
壓縮
mail.txt檔案。 -
將 zip 檔案命名為
mail.zip。
在 Python 中使用 zipfile.ZipFile() 函式開啟一個 Zip 檔案,而無需臨時解壓縮它
下面是一個示例程式,它向你展示瞭如何在不使用 Python 臨時解壓縮的情況下開啟 zip 檔案。按以下方式在讀取模式下使用 zipfile.ZipFile() 函式。
zipfile.ZipFile(file, mode="r")
在這裡,file 是:
- 檔案路徑(字串)
- 一個類似檔案的物件
- 一個類似路徑的物件
例如,
import zipfile
archive = zipfile.ZipFile("mail.zip", "r")
# Let us verify the operation..
txtdata = archive.read("mail.txt")
print(txtdata)
輸出:
b'This is from mail.txt'
在 Python 中使用 ZipFile.open() 函式開啟一個 Zip 檔案,而無需臨時提取它
下面是一個示例,演示瞭如何在不使用 Python 臨時解壓縮的情況下開啟 zip 檔案。
在這裡,我們在讀取模式下使用 open() 函式。
ZipFile.open(name, mode="r")
zip 檔案的成員被視為二進位制檔案類物件。這裡的 name 可以是:
- zip 中的檔名
ZipInfo物件
這是一個例子。
import zipfile
with zipfile.ZipFile("mail.zip") as thezip:
with thezip.open("mail.txt", mode="r") as thefile:
# Let us verify the operation..
print(thefile.read())
輸出:
b'This is from mail.txt'
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe