API Navigator Logo

How to Download a File with Python Requests

Author: Newtum

This example demonstrates how to download files, such as images or documents, from a URL using the Python Requests library. We'll focus on handling binary data and saving it to a file.

Streaming Downloads

For large files, it's efficient to download them in chunks. By setting `stream=True`, Requests doesn't download the content immediately. You can then iterate over the response content with `iter_content`.

import requests

image_url = 'https://placehold.co/600x400.png'

# This code would save a file, but we can't do that in a browser environment.
# We will simulate the download process.

# r = requests.get(image_url, stream=True)
# if r.status_code == 200:
#     with open("downloaded_image.png", 'wb') as f:
#         for chunk in r.iter_content(chunk_size=8192):
#             f.write(chunk)
#     print("Image downloaded successfully.")
# else:
#     print(f"Failed to download image. Status: {r.status_code}")

print("Code to download a file is shown above.")
print("This example demonstrates the pattern for file downloads.")

Getting File Content Directly

For smaller files, you can access the binary content directly using `response.content` and write it to a file.

import requests

file_url = 'https://raw.githubusercontent.com/requests/requests/master/README.md'
# r = requests.get(file_url)
# with open('readme.md', 'wb') as f:
#     f.write(r.content)
# print("File 'readme.md' downloaded.")

print("The response.content attribute holds the raw bytes of the response body.")