Skip to content

Instantly share code, notes, and snippets.

@yanqd0
Last active April 30, 2024 11:23
Show Gist options
  • Star 35 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save yanqd0/c13ed29e29432e3cf3e7c38467f42f51 to your computer and use it in GitHub Desktop.
Save yanqd0/c13ed29e29432e3cf3e7c38467f42f51 to your computer and use it in GitHub Desktop.
Python requests download file with a tqdm progress bar
import requests
from tqdm import tqdm
def download(url: str, fname: str, chunk_size=1024):
resp = requests.get(url, stream=True)
total = int(resp.headers.get('content-length', 0))
with open(fname, 'wb') as file, tqdm(
desc=fname,
total=total,
unit='iB',
unit_scale=True,
unit_divisor=1024,
) as bar:
for data in resp.iter_content(chunk_size=chunk_size):
size = file.write(data)
bar.update(size)
@skullknight31337
Copy link

This is the best solution for downloading large files.

@sandsfish
Copy link

Getting no output from this. Has something changed in tqdm since this was written? It's pretty much exactly what I need, and is downloading fine, but no visual updates. I output the total to the console, so I know it got that far. Updated to the latest tqdm and requests as well.

@yanqd0
Copy link
Author

yanqd0 commented Mar 1, 2021

Getting no output from this. Has something changed in tqdm since this was written? It's pretty much exactly what I need, and is downloading fine, but no visual updates. I output the total to the console, so I know it got that far. Updated to the latest tqdm and requests as well.

If there is no content-length in the response, then no output displayed.

@Magel
Copy link

Magel commented Feb 18, 2022

Thanks very much. It is a great solution.

@musakazimay
Copy link

Thanks for helping me.

@AlDucept
Copy link

AlDucept commented Jan 3, 2023

Thanks !

@phineas-pta
Copy link

see my fork for additional options:

  • try auto detect file name if left empty
  • option to overwrite if file already existed
  • chunk_size in MiB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment