Skip to content

Instantly share code, notes, and snippets.

@sokol8
Forked from ruxi/download_file.py
Created February 3, 2024 05:50
Show Gist options
  • Save sokol8/e9d9e9abb1916f51a7719b4838eda738 to your computer and use it in GitHub Desktop.
Save sokol8/e9d9e9abb1916f51a7719b4838eda738 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