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 bytes chunks (iter_content or response.read()) to a text-mode file ("w") raises TypeError: write() argument must be str, not bytes and would corrupt binary files (ZIPs, images, PDFs) via newline translation on Windows.
  • Why stream=True + iter_content() is critical for large files:
    • Calling requests.get(url) without stream=True downloads the entire HTTP response body into RAM (response.content) before returning—which can exhaust memory on multi-gigabyte files. Streaming in 8192-byte (8 KB) or 65536-byte (64 KB) chunks keeps memory usage flat at a few kilobytes.
  • Check HTTP status codes (response.raise_for_status()):
    • Unlike urllib.request.urlopen() (which raises urllib.error.HTTPError automatically on 404/500 responses), requests.get() does not raise an exception on HTTP errors by default—without response.raise_for_status(), a 404 Not Found HTML error page gets silently saved as your .zip or .pdf file!
  • Always set explicit timeouts (timeout=(connect_timeout, read_timeout)):
    • Both requests and urllib default to timeout=None (hanging forever if a remote server stalls mid-transfer). Pass timeout=(10, 60) (10 seconds to establish connection, 60 seconds max between received data chunks).
  • Avoid deprecated urllib.request.urlretrieve():
    • urlretrieve() is marked as legacy/deprecated in the Python documentation, lacks a timeout parameter (causing scripts to hang indefinitely on stalled connections), and uses global state. Use urlopen() + shutil.copyfileobj() instead.
  • Extracting the filename from Content-Disposition or URL path:
    • If the URL does not end with a clean filename (e.g., https://api.example.com/download?id=99), inspect response.headers.get("Content-Disposition") for filename="..." or fall back to Path(urllib.parse.urlparse(url).path).name or "download.bin".

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.