Download ZIP from URL

Tags: #python #urllib #download #zip #url #request
Author: Hamid Mukhtar
Last update: 2023-05-04 (Created: 2023-04-11)
Description: This notebook will show how to download a ZIP file from a URL using urllib.request.


Import libraries

import os
import shutil
import urllib

Setup Variables

  • url: desired url from which we have to download the zip file
  • headers_1: passing the user agent to surpass the request
  • output_path: path of the file to be save
# Inputs
url = ''
headers_1 = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36'}
# Outputs
output_path = ""


Download zip files

In this example, url is the path of the ZIP file that we want to download. The with statement is used to ensure that the ZIP file is closed properly after it has been read & written. The urllib.request.Request class is used to request the file. The urllib.request.urlopen method is called to open all the files in the archive to the current working directory. The shutil.copyfileobj class is used to open all the files and copy it in the required file as MyFile.zp as f.
# request the file from website
req = urllib.request.Request(url, headers=headers_1)
# open it in a file and write it to save it in local
with urllib.request.urlopen(req) as response, open(output_path, 'wb') as f:
shutil.copyfileobj(response, f)


Display result

The ZIP file has been downloaded and saved in the current directory.
print("✅ ZIP downloaded on:", output_path)