Download a zip file and extract it in memory using Python3

user1720740 picture user1720740 · May 2, 2014 · Viewed 14.9k times · Source

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.

Answer

user1720740 picture user1720740 · May 2, 2014

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.