簡體   English   中英

是否可以使用 python zipfile 庫僅下載 ZIP 文件的一部分

[英]Is it possible to download just part of a ZIP file using python zipfile library

我想知道有什么方法可以只下載 a.rar 或 .zip 文件的一部分而不下載整個文件? 有一個包含文件 A、B、C 和 D 的 zip 文件。我只需要 A。我能以某種方式使用 zipfile 模塊,這樣我只能下載 1 個文件嗎?

我正在嘗試以下代碼:

 r = c.get(file)
    z = ZipFile.ZipFile(BytesIO(r.content)) 
    for file1 in z.namelist():
        if 'time' not in file1:
            print("hi")
            z.extractall(file1,download_path + filename)

此代碼正在下載整個 zip 文件,並且只提取特定的一個。 我能以某種方式只下載我需要的文件嗎? 這里有類似的問題,但它僅顯示 linux 中命令行的方法。該問題解決了如何使用 python 庫來完成的問題。

注釋中提到的@Juggernaut 問題實際上非常有幫助,因為它指出了解決方案的方向。

您需要創建一個Bytes.IO的替代品,該替代品將必要的信息返回給ZipFile 您將需要獲取文件的長度,然后獲取ZipFile要求的所有內容。

這些文件有多大? 真的值得麻煩嗎?

使用 remotezip: https://github.com/gtsystem/python-remotezip 您可以使用 pip 安裝它:

pip install remotezip

使用示例:

from remotezip import RemoteZip


with RemoteZip("https://path/to/zip/file.zip") as zip_file:
    for file in zip_file.namelist():
        if 'time' not in file:
            print("hi")
            zip_file.extract(file, path="/path/to/extract")

請注意,要使用此方法,您從中接收文件的 web 服務器需要支持范圍 header

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM