I want a loading bar that prints "*" every one second and after five seconds has an output of: ***** but instead my program waits fives seconds and prints "*****" all at once.
import time
for i in range(5):
time.sleep(1)
print("*", end="")
I want a loading bar that prints "*" every one second and after five seconds has an output of: ***** but instead my program waits fives seconds and prints "*****" all at once.
import time
for i in range(5):
time.sleep(1)
print("*", end="")
Besides the solution mentioned by @jasonharper in the comment section, another solution is to iteratively delete the last line from stdout:
import time
import sys
def delete_last_line():
"""Use this function to delete the last line in the STDOUT"""
sys.stdout.write('\x1b[1A') # cursor up one line
sys.stdout.write('\x1b[2K') # delete last line
for i in range(1, 6):
delete_last_line()
print("*" * i)
time.sleep(1)
using the "\r"
aka the carriage return can be a good solution to your specific problem. You can see
this section for a better overview of carriage return.
the code for your specific problem:
import time
steps = 5
wait = 1
for i in range(steps):
line = '*'* (i+1) # updating the stars in each iteration
if i < steps-1:
line += '\r' # adding '\r' excluding the last step, otherwise it will clear out the final output
time.sleep(wait)
print(line, end='')