Template request | Bug report | Generate Data Product
Tags: #python #urllib #download #zip #url #request
Author: Hamid Mukhtar
Description: This notebook will show how to download a ZIP file from a URL using urllib.request.
References:
import os
import shutil
import urllib
url
: desired url from which we have to download the zip fileheaders_1
: passing the user agent to surpass the requestoutput_path
: path of the file to be save
# Inputs
url = 'https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-zip-file.zip'
headers_1 = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'}
# Outputs
output_path = "MyFile.zip"
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)
The ZIP file has been downloaded and saved in the current directory.
print("✅ ZIP downloaded on:", output_path)