W3docs

How to download a file over HTTP?

Import the "urllib" module:

  1. Import the "urllib" module:

Import urllib.request in Python

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:

Download a file over HTTP in Python

urllib.request.urlretrieve("http://example.com/file.txt", "local_file.txt")

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

  1. You can also use the "urlopen" function to open the file and then write the contents to a local file:

Open a file over HTTP and write contents to a local file in Python

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:

Download a file over HTTP in Python with sending additional headers

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.