How to Download Files From the Internet in Python using the urllib Module



Python


In this article, we show how to download files from the internet in Python using the urllib module.

We will show 2 methods of doing this.

Both methods use the urllib.request module. The urllib.request module is a Python module for opening and reading URLs.

In order to download files, the full path to the file must be specified.

Therefore, this is not for downloading videos off of youtube. A full path must be specified to the video on the internet, such as www.thiswebsite.com/House-building.mp4

The file can be an image, video, PDF, etc.

So let's see how to do this in code shown below.



Let's now go over this code.

First, we import the urllib.request module, so that we can use its functionality.

Then we use the urllib.request.urlretrieve() function to download a file.

The urllib.request.urlretrieve() function takes in 2 parameters. The first parameter is the full path to the file that you want to download. The second parameter is the name that you want the file to be after it's downloaded.

Let's now go over an alternate way of doing this shown in the code below.



In this code, instead of using the urllib.request.urlretrieve() function, we import urlopen from urllib.request. This is able to retrieve the file from the URL.

We then import copyfileobj from shutil to do the actual file copying.

We create a variable, url, which will store the full path to the file that we want to copy.

We then the urlopen() function and establish our input_file as the url and our output file with whatever name you want it to be.

We then use the copyfileobj() function to download the file from the internet.

So these are 2 possible ways to download files off the internet using the urllib module in Python, assuming you have the full path to the files.


Related Resources

How to Draw a Rectangle in Python using OpenCV

How to Draw a Circle in Python using OpenCV

How to Draw a Line in Python using OpenCV

How to Add Text to an Image in Python using OpenCV

How to Display an OpenCV image in Python with Matplotlib

How to Use Callback functions to Connect Images to Events in Python using OpenCV

How to Check for Multiple Events in Python using OpenCV



HTML Comment Box is loading comments...