How to download a file over HTTP?

  1. Import the "urllib" module:
import urllib.request
  1. Use the "urlretrieve" function from the "urllib" module to download the file. The first argument is the URL of the file, and the second argument is the name of the local file where the data will be saved:
urllib.request.urlretrieve("http://example.com/file.txt", "local_file.txt")

Watch a course Python - The Practical Guide

  1. You can also use the "urlopen" function to open the file and then write the contents to a local file:
response = urllib.request.urlopen("http://example.com/file.txt")
data = response.read()

with open("local_file.txt", "wb") as file:
    file.write(data)
  1. If you need to include additional headers or authentication information, you can use the "Request" class from the "urllib" module:
headers = {"User-Agent": "MyApp"}
req = urllib.request.Request("http://example.com/file.txt", headers=headers)
response = urllib.request.urlopen(req)
data = response.read()

with open("local_file.txt", "wb") as file:
    file.write(data)

Note: Be sure to check the status code of the response to ensure that the download was successful. If the status code is not 200, then there may have been an error with the download.