Search code examples
pythonprogress-barf-stringformat-string

How to show percentage along with progress bar in python?


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?


Solution

  • 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)