A simple progress bar in python — Knowhows
2 min readApr 23, 2024
Read on if you want to add on a cool simplistic progress bar in a terminal in python. This is to print a simple and effective progress bar in python in the terminal.
import sys
def progress_bar(iteration: int, total: int, prefix: str = '', suffix: str = '', decimals: int = 1, length: int = 100, fill: str = '█') -> None:
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
percent = ('{0:.' + str(decimals) + 'f}').format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
sys.stdout.write(f'\r{prefix} |{bar}| {percent}% {suffix}')
sys.stdout.flush()
The above small piece of code will print out this progress bar:
If you only want to print the current percentage and not the entire progress bar, you can just use this small piece of code to fix it up.
import sys
def progress_percent(total: int, count: int) -> None:
"""
Call in a loop to create terminal progress percentage
@params:
total - Required : total iterations (Int)
count - Required : current iteration (Int)
"""
percent = ('{0:.' + str(1) + 'f}').format(100 * (count / float(total)))
sys.stdout.write(f'\r Processing ... {percent}%')
sys.stdout.flush()
The above code will only print out the percentage for the progress
Hope it helps!