python requests module to download file

How to Use Python Requests Module to Download a File

If you're working with Python, you may need to download a file from the web. An easy way to accomplish this is to use the Requests module.

Step 1: Install Requests Module

To use the Requests module, you need to first install it. You can do this using pip, the Python package manager:

pip install requests

Step 2: Send a GET Request

To download a file, you need to send a GET request to the URL where the file is located. Here's an example:

import requests

url = 'https://example.com/file.pdf'
response = requests.get(url)

with open('file.pdf', 'wb') as f:
    f.write(response.content)

In this example, we first import the Requests module. Then, we define the URL of the file we want to download. We send a GET request to that URL using the requests.get method. The response object contains the content of the file. We open a new file in write-binary mode and write the content of the response to it.

Step 3: Check Response Status Code

It's always a good idea to check the status code of the response to make sure the request was successful:

if response.status_code == requests.codes.ok:
    print('File downloaded successfully')
else:
    print('Error downloading file. Status code:', response.status_code)

This code checks if the status code of the response is 200 (OK). If it is, it prints a success message. Otherwise, it prints an error message with the status code.

Alternative: Use urllib

If you don't want to use the Requests module, you can use the built-in urllib module instead:

import urllib.request

url = 'https://example.com/file.pdf'
urllib.request.urlretrieve(url, 'file.pdf')

In this example, we import the urllib.request module. We then use the urlretrieve method to download the file to a local directory.