How to download a file over HTTP with Python?

Sometimes, we want to download a file over HTTP with Python.

In this article, we’ll look at how to download a file over HTTP with Python.

How to download a file over HTTP with Python?

To download a file over HTTP with Python, we can use the urllib.request.urlretrieve method.

For instance, we’ll write:

import urllib.request

photo = urllib.request.urlretrieve(
    "https://i.picsum.photos/id/830/200/300.jpg?hmac=YHS3854_x-GHeQToxsiUmEvBJpDbZOAyixX9nxz61Sg",
    "photo.jpg")
print(photo)

We call urllib.request.urlretrieve with the URL of the file to retrieve and the file name to save the file as respectively.

And we assign the returned file to photo.

Therefore, photo is the photo file object we downloaded onto the disk.

Conclusion

To download a file over HTTP with Python, we can use the urllib.request.urlretrieve method.