How to overwrite previous print on stdout in python?

If I had the following code:

for x in range(10): print x 

I would get a conclusion

 1 2 etc.. 

I would like to do this instead of printing a new line, I want to replace the previous value and overwrite it with a new value on the same line.

+94
python
Mar 24 '11 at 12:50
source share
16 answers

One way is to use the carriage return character ( '\r' ) to return to the beginning of a line without going to the next line:

 for x in range(10): print '{0}\r'.format(x), print 

The comma at the end of the print statement says that it does not advance to the next line. The last print statement moves to the next line, so your prompt will not overwrite your final result.

+100
Mar 24 2018-11-12T00:
source share

Since I ended up here via Google, but I'm using Python 3, here's how it would work in Python 3:

 for x in range(10): print("Progress {:2.1%}".format(x / 10), end="\r") 

The related answer is here: How can I suppress a new line after a print statement?

+91
Feb 17 '14 at 21:56
source share

@Mike DeSimone's answer is likely to work most of the time. But...

 for x in ['abc', 1]: print '{}\r'.format(x), -> 1bc 

This is because '\r' only returns to the beginning of the line, but does not clear the output.

EDIT: better solution (than my previous suggestion below)

If POSIX support is sufficient for you, the following will clear the current line and leave the cursor at the beginning:

 print '\x1b[2K\r', 

It uses the ANSI exit code to clear the terminal line. More information can be found in wikipedia and in this great conversation .

Old answer

The solution (not very good) that I found is as follows:

 last_x = '' for x in ['abc', 1]: print ' ' * len(str(last_x)) + '\r', print '{}\r'.format(x), last_x = x -> 1 

One of the advantages is that it will work on windows as well.

+25
Aug 03 '14 at 13:27
source share

I had the same question before you visited this topic. For me, sys.stdout.write only worked if I correctly flush the ie buffer

 for x in range(10): sys.stdout.write('\r'+str(x)) sys.stdout.flush() 

Without flushing, the result is printed only at the end of the script.

+23
Aug 2 '15 at 23:47
source share

New line suppression and printing \r .

 print 1, print '\r2' 

or write to stdout:

 sys.stdout.write('1') sys.stdout.write('\r2') 
+17
Mar 24 '11 at 12:53
source share

I could not get any of the solutions on this page to work on IPython , but a slight deviation from the @ Mike-Desimone solution completed the task: instead of completing the carriage return line, run the carriage return line:

 for x in range(10): print '\r{0}'.format(x), 

In addition, a second print statement is not required for this approach. A.

+7
Apr 22 '15 at 10:22
source share

Try this:

 import time while True: print("Hi ", end="\r") time.sleep(1) print("Bob", end="\r") time.sleep(1) 

It worked for me. The end="\r" forces to overwrite the previous line.

WARNING!

If you print hi and then print hello using \r , you get hillo because the output of hillo on top of the previous two letters. If you print hi with spaces (which are not displayed here), hi is output. To fix this, print spaces using \r .

+7
Jun 20 '16 at 0:20
source share
 for x in range(10): time.sleep(0.5) # shows how its working print("\r {}".format(x), end="") 

time.sleep (0.5) shows how the previous output is erased and the new output is printed "\ r", when it is at the beginning of the print message, it will delete the previous output before the new output.

+5
Apr 09 '17 at 3:20
source share

The accepted answer is not perfect. The line that was printed first will remain there, and if your second print does not cover the entire new line, you will get garbage text.

To illustrate the problem, save this code as a script and run it (or just look):

 import time n = 100 for i in range(100): for j in range(100): print("Progress {:2.1%}".format(j / 100), end="\r") time.sleep(0.01) print("Progress {:2.1%}".format(i / 100)) 

The output will look something like this:

 Progress 0.0%% Progress 1.0%% Progress 2.0%% Progress 3.0%% 

What works for me is to clear the line before leaving a permanent print. Feel free to adapt to your specific problem:

 import time ERASE_LINE = '\x1b[2K' # erase line command n = 100 for i in range(100): for j in range(100): print("Progress {:2.1%}".format(j / 100), end="\r") time.sleep(0.01) print(ERASE_LINE + "Progress {:2.1%}".format(i / 100)) # clear the line first 

And now it prints as expected:

 Progress 0.0% Progress 1.0% Progress 2.0% Progress 3.0% 
+4
Jul 17 '18 at 20:48
source share

This works on Windows and Python 3.6.

 import time for x in range(10): time.sleep(0.5) print(str(x)+'\r',end='') 
+4
Aug 01 '18 at 17:16
source share

Here's a cleaner, more plug and play version of @ Nagasaki45. Unlike many other answers here, it works correctly with strings of different lengths. This is achieved by clearing a line with the same number of spaces as the length of the last printed line. Will also work on Windows.

 def print_statusline(msg: str): last_msg_length = len(print_statusline.last_msg) if hasattr(print_statusline, 'last_msg') else 0 print(' ' * last_msg_length, end='\r') print(msg, end='\r') sys.stdout.flush() # Some say they needed this, I didn't. print_statusline.last_msg = msg 

using

Just use it like this:

 for msg in ["Initializing...", "Initialization successful!"]: print_statusline(msg) time.sleep(1) 

This little test shows that the lines are cleared correctly, even for different lengths:

 for i in range(9, 0, -1): print_statusline("{}".format(i) * i) time.sleep(0.5) 
+3
May 13 '17 at 10:46 a.m.
source share

To create the bootloader, I used the following:

 for i in range(10): print(i*'.', end='\r') 
+2
Nov 07 '17 at 2:36 on
source share

(Python3) This is what worked for me. If you just use \ 010, then characters will remain in it, so I tweaked it a bit so that it rewrites what was there. It also allows you to have something in front of the first print item and remove only the length of the item.

 print("Here are some strings: ", end="") items = ["abcd", "abcdef", "defqrs", "lmnop", "xyz"] for item in items: print(item, end="") for i in range(len(item)): # only moving back the length of the item print("\010 \010", end="") # the trick! time.sleep(0.2) # so you can see what it doing 
+2
Aug 08 '19 at 0:53
source share

I am a little surprised that no one uses the return character. Here is the one that uses this.

 import sys import time secs = 1000 while True: time.sleep(1) #wait for a full second to pass before assigning a second secs += 1 #acknowledge a second has passed sys.stdout.write(str(secs)) for i in range(len(str(secs))): sys.stdout.write('\b') 
+1
Feb 06 '18 at 20:09
source share

Here is my solution! Windows 10, Python 3.7.1

I'm not sure why this code works, but it completely erases the original line. I compiled this from previous answers. Other answers would simply return the line to the beginning, but if you had a shorter line after that, it would look spoiled as hello turns into byelo .

 import sys #include ctypes if you're on Windows import ctypes kernel32 = ctypes.windll.kernel32 kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7) #end ctypes def clearline(msg): CURSOR_UP_ONE = '\033[K' ERASE_LINE = '\x1b[2K' sys.stdout.write(CURSOR_UP_ONE) sys.stdout.write(ERASE_LINE+'\r') print(msg, end='\r') #example ig_usernames = ['beyonce','selenagomez'] for name in ig_usernames: clearline("SCRAPING COMPLETE: "+ name) 

Conclusion - each line will be rewritten without any old text showing:

 SCRAPING COMPLETE: selenagomez 

The following line (completely rewritten on the same line):

 SCRAPING COMPLETE: beyonce 
0
Dec 19 '18 at 1:12
source share

Here is a simple code that may be useful to you!

 import sys import time for i in range(10): sys.stdout.write("\r" + i) sys.stdout.flush() time.sleep(1) 
-2
Jan 20 '16 at 8:22
source share



All Articles