Skip to content

Instantly share code, notes, and snippets.

@ruxi
Last active February 3, 2024 18:56
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ruxi/5d6803c116ec1130d484a4ab8c00c603 to your computer and use it in GitHub Desktop.
Save ruxi/5d6803c116ec1130d484a4ab8c00c603 to your computer and use it in GitHub Desktop.
python download_file with progressbar using request and tqdm
#!/usr/bin/env python
__author__ = "github.com/ruxi"
__license__ = "MIT"
import requests
import tqdm # progress bar
import os.path
def download_file(url, filename=False, verbose = False):
"""
Download file with progressbar
Usage:
download_file('http://web4host.net/5MB.zip')
"""
if not filename:
local_filename = os.path.join(".",url.split('/')[-1])
else:
local_filename = filename
r = requests.get(url, stream=True)
file_size = int(r.headers['Content-Length'])
chunk = 1
chunk_size=1024
num_bars = int(file_size / chunk_size)
if verbose:
print(dict(file_size=file_size))
print(dict(num_bars=num_bars))
with open(local_filename, 'wb') as fp:
for chunk in tqdm.tqdm(
r.iter_content(chunk_size=chunk_size)
, total= num_bars
, unit = 'KB'
, desc = local_filename
, leave = True # progressbar stays
):
fp.write(chunk)
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment