0

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="")
Known
  • 1
  • 2
  • 9
    You need to add a `flush=True` parameter to your `print()`. Normally, output is automatically flushed every time a newline is printed - but you're never printing one. – jasonharper May 17 '22 at 21:56

2 Answers2

0

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)
joaopfg
  • 1,227
  • 2
  • 9
  • 18
0

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='')