0

I am writing a small python3 script that prints a line in a for loop. after the line is printed, it clears that line and prints another with the percentage going up by one. However, I am struggling to get the for loop to print on two seperate lines at the same time.

If you are unclear about anything or have any questions. Run the script, hopefully you'll see what I mean.

import time
import sys
import os

# you dont need this, it merely clears the terminal screen
os.system('clear')

for c in range(1, 101):
    print("xaishfsaafsjbABSF - " + str(c) + "% |=======   |")

    sys.stdout.write("\033[F") # goes back one line on terminal
    sys.stdout.write("\033[K") # clears that line
    time.sleep(0.03)
    if c == 100:
        print("xaishfsaafsjbABSF - " + str(c) + "% | COMPLETE |")

I have tried adding for z in range(1, 3): above for c in range(1, 101): but that just prints the second one after the first one. I want them to print at the same time on different lines.

  • What do you mean by `for loop to print on two seperate lines at the same time.`? – Minh-Long Luu Sep 27 '20 at 09:58
  • 1
    Does this answer your question? [Overwriting/clearing previous console line](https://stackoverflow.com/questions/36520120/overwriting-clearing-previous-console-line) – Simon Notley Sep 27 '20 at 10:00

2 Answers2

0

Using ANSI escape codes to move the curser up 2 lines:

import time
for i in range(1,21):
    print("Number:",i)
    print("Percent:",i*100/20)
    time.sleep(0.5)
    print("\033[2A", end="") # move up 2 lines
print("\033[2B", end="") # move down 2 lines after the loop
Wups
  • 2,489
  • 1
  • 6
  • 17
0

Just use \r:

import time

for c in range(1, 101):
    print("xaishfsaafsjbABSF - " + str(c) + "% |=======   |\r", end="")
    time.sleep(0.03)
    if c == 100:
        print("xaishfsaafsjbABSF - " + str(c) + "% | COMPLETE |")
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34