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.
Getting Started
To use
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:
f.write(response.read())
This opens a file called
Handling Redirects
One thing to watch out for is URL redirects when trying to download a file. To handle redirects automatically:
import urllib.request
response = urllib.request.urlretrieve("https://example.com/file.zip", "downloaded_file.zip")
The
Additional Tips
Here are some additional tips when using
The