python - 下载并解压 Zip 文件

标签 python

我想从某个网址下载一个 zip 文件,但我不想暂时保存它,因为我知道下载 zip 文件并将其解压到某个地方的唯一方法是创建一个空的 zip 文件,在其中粘贴下载 zip 内容,然后将其解压到正确的文件夹中。但我想下载并解压,而无需创建 zip 文件夹。我尝试了很多东西,但这些都不起作用。有人知道该怎么做吗? (我的代码可能很糟糕,我不知道,但我不太关心)

import io
import zipfile
import requests
import json
import os

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

url = 'https://beatsaver.com'
page = 0
num = 0
req = requests.get(url + '/api/maps/latest/' + str(page), headers=headers)
latest = json.loads(req.text)
for item in latest['docs']:
    print(latest['docs'][num]['downloadURL'])
    dl = requests.get(url + latest['docs'][num]['directDownload'])
    path = './maps/{} - {} - {}'.format(latest['docs'][num]['key'], latest['docs'][num]['name'].replace(':', '').replace('?', ''), latest['docs'][num]['uploader']['username'])
    os.mkdir(path)
    #here is where i want it to download the zip
    num += 1

最佳答案

由于代码原因,无法将其添加为注释。不过,我认为你的意思是这个。但它没有使用 requests

Now this method will not create and save any files. It will directly save the extracted file.

    from io import BytesIO
    from urllib.request import urlopen
    from zipfile import ZipFile
    zipurl = 'http://stash.compjour.org/data/1800ssa.zip'
    with urlopen(zipurl) as zipresp:
        with ZipFile(BytesIO(zipresp.read())) as zfile:
            zfile.extractall('/tmp/mystuff4')

引用:- https://svaderia.github.io/articles/downloading-and-unzipping-a-zipfile/

关于python - 下载并解压 Zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64990197/

相关文章:

python - 连接列表中的 2 个元素

python - 在任何平台上运行使用 cython 编译的 python

python - ASCII 文本可执行文件,带有 CRLF 行终止符

python - 双线性/双三次插值是否独立地在每个颜色 channel 上运行?

python - 如何使用 Python Pandas 在特定日期时间索引之后获取最近的单行

python - 如何将数据分组到1度纬度的箱中?

Python 无法连接到 MySQL 数据库 : OperationalError

python - 其他优于基于 TCL 的 Expect 的解决方案/语言?

python - 验证 JSON 中的多个节点?

python - 将 Pandas 数据框列中的所有值插入函数