The urllib module in Python 3 provides useful functionality for downloading files from the internet directly into your Python programs. In this short tutorial, we'll cover the basics of using urllib to download files.
from urllib.request import urlopen
This allows us to make requests to internet resources and get a file-like response back.
Next, we simply pass the URL of the file we want to download to
response = urlopen("https://example.com/file.zip")
Saving Downloaded Files
To save the downloaded file to disk, we can treat the response as a file-like object and stream the contents to a file on disk. Here's an example:
with open("downloaded_file.zip", "wb") as f:
This opens a file called
One thing to watch out for is URL redirects when trying to download a file. To handle redirects automatically:
response = urllib.request.urlretrieve("https://example.com/file.zip", "downloaded_file.zip")
Here are some additional tips when using