Python - How to download a file from the Internet

By xngo on June 7, 2019

In Python, the easiest way to download a file from the Internet is to use the requests library.

Installation

pip install requests

Download file from the Internet

#!/usr/bin/python3
# Description: How to download a file from the Internet.
 
import requests
 
print('Begin file download with requests')
 
url = '/sites/default/files/page/2019-06/py-download-file.png'  
request = requests.get(url)
 
with open('download-image.png', 'wb') as file:  
    file.write(request.content)
 
# Retrieve HTTP meta-data
print("Status code = {}".format(request.status_code))
print("Content type = {}".format(request.headers['content-type']))
print("Encoding = {}".format(request.encoding))

Output

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.