Python: how to download and extract a ZIP file

Python: how to download and extract a ZIP file

Python offers many modules for working with files, including those compressed in ZIP format. In this article we will see how to download a file via HTTP and decompress it using Python's urllib and zipfile modules.

Python offers many modules for working with files, including those compressed in ZIP format. In this article we will see how to download a file via HTTP and decompress it using Python's urllib and zipfile modules.

To download a file via HTTP, we can use the urlretrieve method of the urllib.request module. For example, to download a file called file.zip from the URL https://example.com/file.zip, we can use the following code:


import urllib.request

url = 'https://example.com/file.zip'
filename = 'file.zip'

urllib.request.urlretrieve(url, filename)

This code will download the file.zip file from the specified URL and will save it in the current working directory.

Once the file is downloaded, we can unzip it using the zipfile form. For example, to unzip the file file.zip in the current directory, we can use the following code:


import zipfile

filename = 'file.zip'

with zipfile.ZipFile(filename, 'r') as zip_ref:
    zip_ref.extractall('.')

In conclusion, with a few lines of code, it is possible to download a file via HTTP and decompress it using Python. This can be very useful when working with large amounts of data or need to automate the download and processing of files from different sources.