Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a zip file and extract it in memory using Python3

I would like to download a zip file from internet and extract it.

I would rather use requests. I don't want to write to the disk.

I knew how to do that in Python2 but I am clueless for python3.3. Apparently, zipfile.Zipfile wants a file-like object but I don't know how to get that from what requests returns.

If you know how to do it with urllib.request, I would be curious to see how you do it too.

like image 299
user1720740 Avatar asked May 02 '14 01:05

user1720740


People also ask

How do I download and save a ZIP file in Python?

If you just want to save the file from the url you can do: urllib. request. urlretrieve(url, filename) .

How do I extract a ZIP file in Python?

Python3. # into a specific location. Import the zipfile module Create a zip file object using ZipFile class. Call the extract() method on the zip file object and pass the name of the file to be extracted and the path where the file needed to be extracted and Extracting the specific file present in the zip.

How do I extract a large zip file in python?

Unzipping a file with Python is straightforward, We can open the archive using the context manager as we did when creating the zip file, then call the ZipFile. extractall() function and specify a path. That's all there is to it.

How do I extract a ZIP file in Jupyter notebook?

Select the . zip file. A pop up appears showing the content of that file. Tap Extract.


2 Answers

I found out how to do it:

request = requests.get(url)
file = zipfile.ZipFile(BytesIO(request.content))

What I was missing :

  • request.content should be used to access the bytes
  • io.BytesIO is the correct file-like object for bytes.
like image 80
user1720740 Avatar answered Sep 17 '22 17:09

user1720740


Here's another approach saving you having to install requests:

    r = urllib.request.urlopen(req)
    with zipfile.ZipFile(BytesIO(r.read())) as z:
        print( z.namelist() )
like image 37
Baz Avatar answered Sep 19 '22 17:09

Baz