Skip to content

Instantly share code, notes, and snippets.

@suptejas
Created December 25, 2020 15:42
Show Gist options
  • Save suptejas/1b93bbdd296b42f0b2247e331138d0f8 to your computer and use it in GitHub Desktop.
Save suptejas/1b93bbdd296b42f0b2247e331138d0f8 to your computer and use it in GitHub Desktop.
Python Download File With Progress Bar Using Requests
from colorama import Fore
import requests
import sys
# import cursor # Use this if you want to hide or show cursor for a better terminal experience
def download(url: str, download_extension: str, file_path: str, show_progress_bar=True):
'''
Downloads A File from a URL And Saves It To A location
url `(str)`: Link or URL to download the file from.
download_extension`(string)`: Extension for the file downloaded like `.exe` or `.txt`.
file_path`(string)`: Path to save the file to.
Examples(`'C:\\Users\\name\\Downloads'`, `'~/Desktop'`)
show_progress_bar `[Optional]` `(bool)`: Whether or not to show the progress bar while downloading.
>>> download('https://atom.io/download/windows_x64', '.exe', 'C:\MyDir\Installer')
'''
# cursor.hide() # Use This If You Want to Hide The Cursor While Downloading The File In The Terminal
try:
with open(f'{file_path}{download_extension}', 'wb') as f:
# Get Response From URL
response = requests.get(url, stream=True)
# Find Total Download Size
total_length = response.headers.get('content-length')
# Number Of Iterations To Write To The File
chunk_size = 4096
if total_length is None:
f.write(response.content)
else:
dl = 0
full_length = int(total_length)
# Write Data To File
for data in response.iter_content(chunk_size=chunk_size):
dl += len(data)
f.write(data)
if show_progress_bar:
complete = int(25 * dl / full_length)
fill_c = Fore.GREEN + '=' * complete # Replace '=' with the character you want like '#' or '$'
unfill_c = Fore.LIGHTBLACK_EX + '-' * (25 - complete) # Replace '-' with the character you want like ' ' (whitespace)
sys.stdout.write(
f'\r{fill_c}{unfill_c} {Fore.RESET} {round(dl / 1000000, 1)} / {round(full_length / 1000000, 1)} MB {Fore.RESET}')
sys.stdout.flush()
except KeyboardInterrupt:
print(f'\n{Fore.RED}Download Was Interrupted!{Fore.RESET}')
# cursor.show() # Unhide Cursor If You Have Previously Hidden It
# Example usage :
# download('https://atom.io/download/windows_x64', '.exe', r'C:\Users\yourname\Desktop\Installer')
# Downloads The Atom Installer With Filename Installer.exe to Desktop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment