Python Requests Download File From URL
Python Requests is a widely used library for making HTTP requests in Python. This library allows us to send HTTP requests using Python, which makes it easy to work with APIs and web services. In this article, we will learn how to download a file from a URL using Python Requests library.
Step 1: Install Python Requests Library
The first step is to install the Python Requests library. You can install this library using the following command:
!pip install requests
Step 2: Download File from URL
After installing the Requests library, you can download a file from a URL using the following code:
import requests
url = 'https://example.com/file.txt'
r = requests.get(url)
with open('file.txt', 'wb') as f:
f.write(r.content)
In this code, we first import the Requests library. We then specify the URL of the file that we want to download. We use the requests.get()
method to send an HTTP GET request to the specified URL. This method returns a Response
object that contains the content of the response.
We then create a new file called file.txt
in binary write mode and write the content of the response to this file using the f.write()
method.
Alternative Method: Using urllib Package
You can also download a file from a URL using the urllib package in Python. The urllib package is part of the Python standard library and does not require any additional installation.
import urllib.request
url = 'https://example.com/file.txt'
urllib.request.urlretrieve(url, 'file.txt')
In this code, we import the urllib.request
module. We then specify the URL of the file that we want to download. We use the urlretrieve()
method to download the file and save it to the specified file path.
Both methods will download the file from the URL and save it to the specified file path.