How overwrite many print lines in the while loop

I want to ovewrite 2 separate print lines in while True loop. I tried \r and \n but it is not working. When using \r \n override only 1 line or 2 line prints continously.how i fix this?

import sys
import time
tot = 5
new = 2
while True:
    
    sys.stdout.write('{0}\n\r'.format(tot))
    sys.stdout.write('{0}\n\r'.format(new))
    sys.stdout.flush()
    time.sleep(1)
    tot += 1
    new += 1

Upvotes: 0

Views: 1340

Answers (2)

hostingutilities.com
hostingutilities.com

Reputation: 9519

\r brings you to the beginning of the line where you will start overwriting stuff.

\n adds a newline

\n\r takes you to the next line, and then bring you to the beginning of that line, which is already a blank new line, and so the \r isn't actually doing anything and this is the same as just doing \n.

If you only wish to overwrite a single line you can do this with \r followed by your text. Make sure that whatever you print out has enough spaces at the end of it to make it the same length as the line you are overwriting, otherwise, you'll end up with part of the line not getting overwritten.

But since you've clarified that you need to overwrite multiple lines, things are a little bit trickier. Carriage returns (\r) were originally created to help with problems early printers had (This Wikipedia article explains these problems). There is a completely different mechanism for overwriting multiple lines that isn't exposed natively by Python, but this Stack Overflow question lists a few 3rd party libraries you can install that will help you accomplish this.

Upvotes: 1

jr15
jr15

Reputation: 452

To overwrite the previous line, you need to have not yet output a newline. So I don't think you can overwrite multiple lines, sadly. To do one though, try something like this:

while some_condition:
    sys.stdout.write("\r{0}".format("your text here"))
    sys.stdout.flush()

The \r here (called a "carriage return") moves the printing cursor back to the beginning of the line (ie, to right after the most recent newline \n). You cannot go back farther than that, though.

Upvotes: 0

Related Questions