-
-
Save chbrandt/70b9f500329c38927e22b0853b4f08a2 to your computer and use it in GitHub Desktop.
python download_file with progressbar using request and tqdm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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