In this article we will see how to download a file in Python with the requests module.
This module allows GET requests to be made as data streams which will then be reassembled into the final destination file as they are received from the remote source.
import requests
def download_file(url, filename):
try:
r = requests.get(url, stream=True)
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
return True
except requests.exceptions.RequestException:
return False
Our function will return a boolean value which will indicate the status of the operation just performed. The file will be saved in the path specified with the filename
parameter.