How to show percentage along with progress bar in python?

Viewed 501

In python I can show a progress bar:

import time 
print("0%\u2502{:>21s}0%".format("\u2502"), end='')
print("\b"*23,end='')
for _ in range(20):
    print("\u2588", end='')
    time.sleep(.05)

I would like to also show the percentage. How can I do that?

2 Answers

This is how I would approach this task

import time
import sys

bar = ''
for i in range(100):
    bar += "\u2588"
    sys.stdout.write(bar+"\r%d%%" % i)
    sys.stdout.flush()
    time.sleep(0.05)

Basically, the bar string is containing the progress bar that gets printed on the console.

Use sys.stdout.write() and \r to print a new string with the percentage and progress bar over the previous line each time.

import time
import sys

for x in range(21):
    sys.stdout.write("\r{:>3}%\u2502{:<20}\u2502".format(x * 5, "\u2588" * x))
    time.sleep(.05)
Related