简体   繁体   English

下载并解压 Zip 文件

[英]Download and Extract Zip file

I want to download a zip file from an url but i don't want to save it temporarily because, the only way i know to download and extract a zip file to somewhere is to create an empty zipfile where will be paste the downloaded zip content and then, extract that in the correct folder.我想从一个 url 下载一个 zip 文件,但我不想暂时保存它,因为我知道下载一个 zip 文件并将其解压缩到某个地方的唯一方法是创建一个空的 zip 文件,在那里将粘贴下载的 zip 内容然后,将其解压缩到正确的文件夹中。 But i want to download and extract without having to create a zip folder.但我想下载和解压缩而不必创建 zip 文件夹。 I tried a bunch of things but none of these works.我尝试了很多东西,但这些都不起作用。 Does someone know how to do that ?有人知道怎么做吗? (my code is maybe bad, i don't know but i don't really care that much) (我的代码可能很糟糕,我不知道,但我不太在意)

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

Could not add this as a comment because of the code.由于代码原因,无法将此添加为注释。 However, I think you mean this.It is not using requests though.但是,我认为您是这个意思。不过它没有使用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')

Reference:- https://svaderia.github.io/articles/downloading-and-unzipping-a-zipfile/参考:- https://svaderia.github.io/articles/downloading-and-unzipping-a-zipfile/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM