Skip to content

Q&A · Answered

How to download files in Python

asked 9 months, 1 week ago 1200 views 1 answer
6

What is the correct way to download files from URLs in Python?

1 Answer

One accepted
24

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
import requests

# Simple download
url = 'https://example.com/file.zip'
response = requests.get(url)

with open('file.zip', 'wb') as f:
    f.write(response.content)

# Stream large files
with requests.get(url, stream=True) as r:
    r.raise_for_status()
    with open('file.zip', 'wb') as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)

# With progress
from tqdm import tqdm
total_size = int(r.headers.get('content-length', 0))
with tqdm(total=total_size) as pbar:
    for data in r.iter_content(chunk_size=1024):
        pbar.update(len(data))

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.