Use requests.get(url, stream=True, timeout=30) and iterate over response.iter_content(chunk_size=8192) while writing chunks to a binary file (open(dest, "wb"))—which streams the download in constant memory regardless of file size—or use Python’s built-in urllib.request.urlopen() when zero third-party dependencies are allowed.
Basic Example
from pathlib import Path
import requests
url = "[https://example.com/archive.zip](https://example.com/archive.zip)"
dest = Path("archive.zip")
# 1. Recommended (third-party `requests`): Stream chunks safely with error & timeout handling
with requests.get(url, stream=True, timeout=(10, 60)) as response:
response.raise_for_status() # Raises HTTPError on 4xx / 5xx responses
with open(dest, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk: # Filter out keep-alive chunks
f.write(chunk)
print(f"Saved {dest.stat().st_size} bytes to {dest}")
# 2. Zero-dependency standard library alternative (`urllib.request` + `shutil`)
import shutil
import urllib.request
with urllib.request.urlopen(url, timeout=30) as response, open("archive.zip", "wb") as f:
shutil.copyfileobj(response, f)
Key Details & Edge Cases
- Always open the destination file in binary mode (
"wb"):- Writing raw
byteschunks (iter_contentorresponse.read()) to a text-mode file ("w") raisesTypeError: write() argument must be str, not bytesand would corrupt binary files (ZIPs, images, PDFs) via newline translation on Windows.
- Writing raw
- Why
stream=True+iter_content()is critical for large files:- Calling
requests.get(url)withoutstream=Truedownloads the entire HTTP response body into RAM (response.content) before returning—which can exhaust memory on multi-gigabyte files. Streaming in8192-byte (8 KB) or65536-byte (64 KB) chunks keeps memory usage flat at a few kilobytes.
- Calling
- Check HTTP status codes (
response.raise_for_status()):- Unlike
urllib.request.urlopen()(which raisesurllib.error.HTTPErrorautomatically on 404/500 responses),requests.get()does not raise an exception on HTTP errors by default—withoutresponse.raise_for_status(), a404 Not FoundHTML error page gets silently saved as your.zipor.pdffile!
- Unlike
- Always set explicit timeouts (
timeout=(connect_timeout, read_timeout)):- Both
requestsandurllibdefault totimeout=None(hanging forever if a remote server stalls mid-transfer). Passtimeout=(10, 60)(10 seconds to establish connection, 60 seconds max between received data chunks).
- Both
- Avoid deprecated
urllib.request.urlretrieve():urlretrieve()is marked as legacy/deprecated in the Python documentation, lacks atimeoutparameter (causing scripts to hang indefinitely on stalled connections), and uses global state. Useurlopen()+shutil.copyfileobj()instead.
- Extracting the filename from
Content-Dispositionor URL path:- If the URL does not end with a clean filename (e.g.,
https://api.example.com/download?id=99), inspectresponse.headers.get("Content-Disposition")forfilename="..."or fall back toPath(urllib.parse.urlparse(url).path).name or "download.bin".
- If the URL does not end with a clean filename (e.g.,
Comparison of HTTP File Download Methods in Python
| Method | Dependency | Memory Usage (Large Files) | Raises on HTTP 4xx/500? | Best Used When |
|---|---|---|---|---|
requests.get(..., stream=True) |
requests (3rd-party) |
Constant ($O(1)$) via iter_content() |
Yes (with .raise_for_status()) |
General-purpose synchronous file downloads of any size in production scripts. |
urllib.request.urlopen + shutil.copyfileobj |
Standard library | Constant ($O(1)$) | Yes (HTTPError) |
Zero-dependency environments, bootstrap installers, or minimal containers. |
httpx.stream("GET", url) |
httpx (3rd-party) |
Constant ($O(1)$) | Yes (with .raise_for_status()) |
Modern async (async with client.stream(...)) or HTTP/2 download pipelines. |
requests.get(url).content |
requests (3rd-party) |
$O(\text{file size})$ in RAM | Yes (with .raise_for_status()) |
Small payloads (< 10 MB) like JSON files, icons, or small thumbnails. |
urllib.request.urlretrieve() (Avoid) |
Standard library | Constant ($O(1)$) | Yes | Legacy code only—lacks timeout support and is marked legacy in Python docs. |
You must log in or register to comment.
