How to Download Files from Urls With Python
Last Updated :
24 Apr, 2025
Here, we have a task to download files from URLs with Python. In this article, we will see how to download files from URLs using some generally used methods in Python.
Download Files from URLs with Python
Below are the methods to Download files from URLs with Python:
Download Files From URLs Using 'requests' Module
In this example, below Python code utilizes the `requests` library to download a PDF file from a specified URL (`'https://media.geeksforgeeks.org/wp-content/uploads/20240226121023/GFG.pdf'`). It checks the HTTP response status code, and if it's 200 (OK), the content is saved to a local file named 'research_Paper_1.pdf'.
Python3
import requests
url = 'https://media.geeksforgeeks.org/wp-content/uploads/20240226121023/GFG.pdf'
response = requests.get(url)
file_Path = 'research_Paper_1.pdf'
if response.status_code == 200:
with open(file_Path, 'wb') as file:
file.write(response.content)
print('File downloaded successfully')
else:
print('Failed to download file')
Output:
File downloaded successfully
Download Files From Urls Using 'urllib3' module:
In this example, below Python code uses the `urllib.request` module to download a PDF file from the specified URL (`'https://media.geeksforgeeks.org/wp-content/uploads/20240226121023/GFG.pdf'`). The `urlretrieve` function saves the content to a local file named 'research_Paper_2.pdf'.
Python3
import urllib.request
url = 'https://media.geeksforgeeks.org/wp-content/uploads/20240226121023/GFG.pdf'
file_Path = 'research_Paper_2.pdf'
urllib.request.urlretrieve(url, file_Path)