Download and Extract Zip file

Viewed 1295

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. But i want to download and extract without having to create a zip folder. 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
1 Answers

Could not add this as a comment because of the code. However, I think you mean this.It is not using requests though.

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/

Related