As far as I can tell, the proper way to do this in Python 2 is:

import requests, zipfile, StringIO
r = requests.get(zip_file_url, stream=True)
z = zipfile.ZipFile(StringIO.StringIO(r.content))
z.extractall()

of course you'd want to check that the GET was successful with r.ok.

For python 3+, sub the StringIO module with the io module and use BytesIO instead of StringIO: Here are release notes that mention this change.

import requests, zipfile, io
r = requests.get(zip_file_url)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall("/path/to/destination_directory")
Answer from yoavram on Stack Overflow
Top answer
1 of 9
320

As far as I can tell, the proper way to do this in Python 2 is:

import requests, zipfile, StringIO
r = requests.get(zip_file_url, stream=True)
z = zipfile.ZipFile(StringIO.StringIO(r.content))
z.extractall()

of course you'd want to check that the GET was successful with r.ok.

For python 3+, sub the StringIO module with the io module and use BytesIO instead of StringIO: Here are release notes that mention this change.

import requests, zipfile, io
r = requests.get(zip_file_url)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall("/path/to/destination_directory")
2 of 9
85

Most people recommend using requests if it is available, and the requests documentation recommends this for downloading and saving raw data from a url:

import requests 

def download_url(url, save_path, chunk_size=128):
    r = requests.get(url, stream=True)
    with open(save_path, 'wb') as fd:
        for chunk in r.iter_content(chunk_size=chunk_size):
            fd.write(chunk)

Since the answer asks about downloading and saving the zip file, I haven't gone into details regarding reading the zip file. See one of the many answers below for possibilities.

If for some reason you don't have access to requests, you can use urllib.request instead. It may not be quite as robust as the above.

import urllib.request

def download_url(url, save_path):
    with urllib.request.urlopen(url) as dl_file:
        with open(save_path, 'wb') as out_file:
            out_file.write(dl_file.read())

Finally, if you are using Python 2 still, you can use urllib2.urlopen.

from contextlib import closing

def download_url(url, save_path):
    with closing(urllib2.urlopen(url)) as dl_file:
        with open(save_path, 'wb') as out_file:
            out_file.write(dl_file.read())
🌐
Filling the gaps
svaderia.github.io › articles › downloading-and-unzipping-a-zipfile
Downloading and Unzippig a Zip File - Filling the gaps
August 18, 2017 - #!/usr/bin/python3 from urllib.request import urlopen from zipfile import ZipFile zipurl = 'Valid URL to zip file' # Download the file from the URL zipresp = urlopen(zipurl) # Create a new file on the hard drive tempzip = open("/tmp/tempfile.zip", "wb") # Write the contents of the downloaded file into the new file tempzip.write(zipresp.read()) # Close the newly-created file tempzip.close() # Re-open the newly-created file with ZipFile() zf = ZipFile("/tmp/tempfile.zip") # Extract its contents into <extraction_path> # note that extractall will automatically create the path zf.extractall(path = '<extraction_path>') # close the ZipFile instance zf.close()
Discussions

I made RemoteZipFile to download individual files from INSIDE a .zip
That's pretty smart actually. Nice one. More on reddit.com
🌐 r/Python
31
277
July 14, 2022
Trying to scrape and download zipfiles
I have tried a million codes and none are working to scrape this website and download and unzip the csv zipfiles. any help or direction would be appreciated!!! https://www.ercot.com/mp/data-products/data-product-details… More on discuss.python.org
🌐 discuss.python.org
8
0
October 4, 2023
Web scraping and download zipfiles
I am relatively new to python and am trying to automate some analysis. I’m looking to write a code that will go to this website Data Product Details and download the zip files. Then, save a specific excel file in the zip file to a specific file path on my computer. anyone have experience ... More on discuss.python.org
🌐 discuss.python.org
6
0
May 22, 2024
Download Zip Files from a website using python

You sound like a programmer to me. Good job yo!

Edit: debug, debug, debug

More on reddit.com
🌐 r/Python
2
3
June 4, 2015
🌐
GitHub
gist.github.com › hantoine › c4fc70b32c2d163f604a8dc2a050d5f6
Download and extract a ZIP file in Python · GitHub
Download and extract a ZIP file in Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Python
docs.python.org › 3 › library › zipfile.html
zipfile — Work with ZIP archives
February 23, 2026 - Source code: Lib/zipfile/ The ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this ...
🌐
Medium
stereopickle.medium.com › how-to-download-unzip-zip-files-in-python-5f326bb1a829
How to Download & Unzip Zip files in Python | by Eunjoo Byeon | Medium
December 27, 2020 - How to Download & Unzip Zip files in Python Just a quick tutorial Processing a large amount of data on a local machine can be a hassle sometimes, especially if our primary purpose is rather …
🌐
Reddit
reddit.com › r/python › i made remotezipfile to download individual files from inside a .zip
r/Python on Reddit: I made RemoteZipFile to download individual files from INSIDE a .zip
July 14, 2022 -

Link to unzip-http on Github

Hey everyone, this was originally part of my new readysetdata library, but it turned to be so useful that I cleaned it up and turned it into its own library.

Sometimes data is published in giant GB or even TB .zip archives, and you may only need a couple of files--sometimes you only just want to know what files are inside the archive! But the .zip central directory is at the end of the file, so you have to download the whole thing for any zip utility to work.

RemoteZipFile is a ZipFile-like object that can extract individual files using HTTP Range Requests. Given a URL it will generate ZipInfo objects for the files inside (now including the date/time), and allow you to open() a file and do whatever you want with it. Streaming (and read-only) of course.

I've also incorporated it into VisiData so if you use that, you can look forward in the next version (should be released in the next week or two) to just browsing online .zip files like it's nobody's business.

Both the library and command-line application can be installed from PyPI via pip install unzip-http. Share and enjoy!

Find elsewhere
🌐
Python Guides
pythonguides.com › download-zip-file-from-url-using-python
Download And Extract ZIP Files From A URL In Python
December 29, 2025 - The wget library is another alternative for downloading files, especially useful for large files due to its robust handling of network issues. ... import wget from zipfile import ZipFile import os # URL of the ZIP file url = 'https://pythonguides.com/....../MyPDFFile.zip' file_name = wget.download(url) # Extract the downloaded ZIP file with ZipFile(file_name, 'r') as zip_file: zip_file.extractall() print("Files extracted successfully") # Optional: Remove the ZIP file after extraction os.remove(file_name)
🌐
Real Python
realpython.com › python-zipfile
Python's zipfile: Manipulate Your ZIP Files Efficiently – Real Python
January 26, 2025 - GitHub uses ZIP files to package software projects when you download them to your local computer. For example, you can download the exercise solutions for Python Basics: A Practical Introduction to Python 3 book in a ZIP file, or you can download any other project of your choice.
🌐
Compciv
compciv.org › practicum › shakefiles › b-downloading-the-shakespeare-zip
Downloading and saving the Shakespeare zip with requests | Computational Methods in the Civic Sphere at Stanford University
We simply downloaded and saved it to a path. This is going to seem exceedingly pedantic. On Mac OSX and Linux, the following file path: ... The differences between operating systems means that, just to be safe, it's better to defer the naming of a file path to the join() function that is part of Python's os.path module (which is automatically included if you ran import os). ... >>> mydirname = 'tempdata' >>> myfilename = 'somefile.zip' >>> myfullfilename = os.path.join(mydirname, myfilename) >>> print(myfullfilename) tempdata/somefile.zip # note that this will be different on Windows machines
🌐
Real Python
realpython.com › python-download-file-from-url
How to Download Files From URLs With Python – Real Python
January 25, 2025 - Then, you can download and save the file by calling urlretrieve() and passing in the URL and optionally your filename: ... >>> urlretrieve(url, filename) ('gdp_by_country.zip', <http.client.HTTPMessage object at 0x7f06ee7527d0>)
🌐
Esri Community
community.esri.com › t5 › python-questions › python-download-zip-file › td-p › 1094346
Solved: Python - Download Zip File - Esri Community
March 22, 2022 - from arcgis.gis import GIS # Python Standard Library Modules from pathlib import Path, PurePath from zipfile import ZipFile public_data_item_id = '123' anon_gis = GIS(username="123", password="123") data_item = anon_gis.content.get(public_data_item_id) data_path = Path('C:\123') if not data_path.exists(): data_path.mkdir() zip_path = data_path.joinpath('PAData.zip') extract_path = data_path.joinpath('PADataDatasets') data_item.download(save_path=data_path) print (PurePath(zip_path)) Solved! Go to Solution. ... Hello @BlakeTerhune Please see screenshots and python script. i also set it up on task scheduler. it was working running since September 2021 until stop recently. I haven't change any script and task scheduler. For some reasons, my zip file 'PaFiles.gdb' stopped working.
🌐
Reddit
reddit.com › r/python › download zip files from a website using python
r/Python on Reddit: Download Zip Files from a website using python
June 4, 2015 -

I'll be the first to admit I'm not a programmer and am more of a hack it together kind of guy. But I thought this was a bit of an accomplishment on my part. I created this python script to scrape through a website and download all the .zip files on it and save them to a new directory.

Small challenges that I needed to over come included: The path to the zip files were relative paths and there for I needed to concatenate the paths in order for the urls to work. I needed to add error handling as one of the links was known to produce a 404. I also needed to give each downloaded zip file a new unique name, so needed to parse the zip file name out of the url.

#Author: Bellerophon_
#Date Created: 04/12/15
#Usage: Used to scrape a website for links that end in .zip and list them
#Requirements: BeautifulSoup lib
#Notes: 

import urllib2
from urllib2 import Request, urlopen, URLError
#import urllib
import os
from bs4 import BeautifulSoup


#Create a new directory to put the files into
#Get the current working directory and create a new directory in it named test
cwd = os.getcwd()
newdir = cwd +"\\test"
print "The current Working directory is " + cwd
os.mkdir( newdir, 0777);
print "Created new directory " + newdir
newfile = open('zipfiles.txt','w')
print newfile


print "Running script.. "
#Set variable for page to be open and url to be concatenated 
url = "http://www.elections.bc.ca"
page = urllib2.urlopen('http://www.elections.bc.ca/index.php/maps/electoral-maps/geographic-information-system-spatial-data-files-2012/').read()

#File extension to be looked for. 
extension = ".zip"

#Use BeautifulSoup to clean up the page
soup = BeautifulSoup(page)
soup.prettify()

#Find all the links on the page that end in .zip
for anchor in soup.findAll('a', href=True):
    links = url + anchor['href']
    if links.endswith(extension):
        newfile.write(links + '\n')
newfile.close()

#Read what is saved in zipfiles.txt and output it to the user
#This is done to create presistent data 
newfile = open('zipfiles.txt', 'r')
for line in newfile:
    print line + '/n'
newfile.close()

#Read through the lines in the text file and download the zip files.
#Handle exceptions and print exceptions to the console
with open('zipfiles.txt', 'r') as url:
    for line in url:
        if line:
            try:
                ziplink = line
                #Removes the first 48 characters of the url to get the name of the file
                zipfile = line[48:]
                #Removes the last 4 characters to remove the .zip
                zipfile2 = zipfile[:3]
                print "Trying to reach " + ziplink
                response = urllib2.urlopen(ziplink)
            except URLError as e:
                if hasattr(e, 'reason'):
                    print 'We failed to reach a server.'
                    print 'Reason: ', e.reason
                    continue
                elif hasattr(e, 'code'):
                    print 'The server couldn\'t fulfill the request.'
                    print 'Error code: ', e.code
                    continue
            else:
                zipcontent = response.read()
                completeName = os.path.join(newdir, zipfile2+ ".zip")
                with open (completeName, 'w') as f:
                    print "downloading.. " + zipfile
                    f.write(zipcontent)
                    f.close()
print "Script completed"
🌐
GeeksforGeeks
geeksforgeeks.org › python › working-zip-files-python
Working with ZIP Files in Python - GeeksforGeeks
January 19, 2026 - Python provides the built-in zipfile module to work with ZIP files.
🌐
PyPI
pypi.org › project › zip-files
zip-files · PyPI
Uploaded Apr 21, 2021 Python 3 · Details for the file zip_files-0.4.1.tar.gz. Download URL: zip_files-0.4.1.tar.gz · Upload date: Apr 21, 2021 · Size: 43.5 kB · Tags: Source · Uploaded using Trusted Publishing? No · Uploaded via: twine/3.4.1 importlib_metadata/3.10.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.8.1 ·
      » pip install zip-files
    
Published   Apr 21, 2021
Version   0.4.1
🌐
TechOverflow
techoverflow.net › 2018 › 01 › 16 › downloading-reading-a-zip-file-in-memory-using-python
Downloading & reading a ZIP file in memory using Python | TechOverflow
January 15, 2018 - In Python3 can use io.BytesIO together with zipfile (both are present in the standard library) to read it in memory. The following example function provides a ready-to-use generator based approach on iterating over the files in the ZIP: ... import requests import io import zipfile def download_extract_zip(url): """ Download a ZIP file and extract its contents in memory yields (filename, file-like object) pairs """ response = requests.get(url) with zipfile.ZipFile(io.BytesIO(response.content)) as thezip: for zipinfo in thezip.infolist(): with thezip.open(zipinfo) as thefile: yield zipinfo.filename, thefile
Top answer
1 of 1
8

There are 2 main steps (each with its own set of substeps) that need to be followed:

  1. Download and unpack the interpreter on your machine:

    1. Download the .zip file (e.g. [Python]: python-3.6.5-embed-amd64.zip) on your computer, in an empty dir (on my machine it's: "e:\Work\Dev\StackOverflow\q050818078\python36x64")

    2. Unzip the file (some (.pyd, .dll, .exe, .zip, ._pth) files will appear). At the end, you can delete the .zip file that you downloaded in previous step

  2. Configure PyCharm to use it:

    Notes:

    • In order for the images below to be a small as possible (from size and display PoV), I have reduced the sizes of all windows from their default values

    • Some PyCharm stuff is specific to my machine / environment, (obviously) that will be different in your case

    • The script that I used for testing, is a dummy one that just prints some paths (that's why I didn't add it as code, it's just in the 1st image)

    • I only illustrate the minimal required steps to get you going, so even if for some steps there are options to customize them, I'm not going to mention them

    • I am using PyCharm Community Edition 2017.3.3 (in other versions things could be slightly different)

    Steps:

    1. In PyCharm main window (considering your project is open), go to menu File -> Settings...:

      You could also go to File -> Default Settings..., check [JetBrains]: Project and IDE Settings for differences between them.

    2. In the Settings window, click Project Interpreter -> Show All (you might need to scroll down - if you have multiple interpreters configured)

    3. In the Project Interpreters window, click the Add button (green + (plus) on upper right side). Also, you might have to click an Add Local... control that appears when you click Add

    4. In the Add Local Python Interpreter, make sure to:

      • Check Exiting environment radio button

      • Click the ... (Browse) button

    5. In the Select Python Interpreter window, go to the folder where you unzipped the file at #1.1., select python.exe and then click OK

    6. Click the OK button in all the windows opened at previous steps (in reversed order), until you're back to main window

In order to test, on the code editor window, right click and from the popup menu choose Run 'code'. Here's console output window content:

E:\Work\Dev\StackOverflow\q050818078\python36x64\python.exe E:/Work/Dev/StackOverflow/q050818078/src/code.py
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32

E:\Work\Dev\StackOverflow\q050818078\python36x64\python.exe
E:\Work\Dev\StackOverflow\q050818078\src\code.py

Process finished with exit code 0

As a final note, naming the test file code.py was "a bit" uninspired, as there is such a module in Python's standard library (in the meantime, I renamed it to code00.py), but I don't feel like doing all the screenshots (that contain it) again.

Might contain useful info on possible related problems:

  • [SO]: PyCharm doesn't recognize installed module (@CristiFati's answer)

  • [SO]: How to install a package for a specific Python version on Windows 10? (@CristiFati's answer)

  • [SO]: Create Windows Python virtualenv with a specific version of Python (@CristiFati's answer)

Top answer
1 of 10
118

Below is a code snippet I used to fetch zipped csv file, please have a look:

Python 2:

from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen

resp = urlopen("http://www.test.com/file.zip")
myzip = ZipFile(StringIO(resp.read()))
for line in myzip.open(file).readlines():
    print line

Python 3:

from io import BytesIO
from zipfile import ZipFile
from urllib.request import urlopen
# or: requests.get(url).content

resp = urlopen("http://www.test.com/file.zip")
myzip = ZipFile(BytesIO(resp.read()))
for line in myzip.open(file).readlines():
    print(line.decode('utf-8'))

Here file is a string. To get the actual string that you want to pass, you can use zipfile.namelist(). For instance,

resp = urlopen('http://mlg.ucd.ie/files/datasets/bbc.zip')
myzip = ZipFile(BytesIO(resp.read()))
myzip.namelist()
# ['bbc.classes', 'bbc.docs', 'bbc.mtx', 'bbc.terms']
2 of 10
81

My suggestion would be to use a StringIO object. They emulate files, but reside in memory. So you could do something like this:

# get_zip_data() gets a zip archive containing 'foo.txt', reading 'hey, foo'

import zipfile
from StringIO import StringIO

zipdata = StringIO()
zipdata.write(get_zip_data())
myzipfile = zipfile.ZipFile(zipdata)
foofile = myzipfile.open('foo.txt')
print foofile.read()

# output: "hey, foo"

Or more simply (apologies to Vishal):

myzipfile = zipfile.ZipFile(StringIO(get_zip_data()))
for name in myzipfile.namelist():
    [ ... ]

In Python 3 use BytesIO instead of StringIO:

import zipfile
from io import BytesIO

filebytes = BytesIO(get_zip_data())
myzipfile = zipfile.ZipFile(filebytes)
for name in myzipfile.namelist():
    [ ... ]