'Is there a way to remove prevous prints?
So i am currently trying to make something that will print .
and remove it then print ..
and also remove it then print ...
When i tried using sys module to remove the prevous text this was the output: lol [Ktest
so it basically adds a [K
to the next line.
I also tried using another method so instead of removing the prevous text it would just add onto it like:
import time
print("lol",end="")
time.sleep(1)
print("test")
it did work in IDLE but when i tried to use it by opening the file in the command promt it waited for 1 second and then just gave loltest
without any delay between them. So nothing i found in the internet worked for me.
Solution 1:[1]
You may print with the keyword argument end
to append the special character '\r'
to the end of the line.
E.g.
import time
print(".", end='\r')
time.sleep(2)
print("..", end='\r')
time.sleep(2)
print("...", end='\r')
time.sleep(2)
'\r'
is carriage return and will return to the start of the line in some terminals, from where you can overwrite the text you just printed. Note that the behaviour might differ between terminals though.
Solution 2:[2]
To print over the prvious print, you can use end="\r
.
import time
print("lol", end="\r")
time.sleep(1)
print("test")
for i in range(4):
print("."*i, end="\r")
time.sleep(1)
Solution 3:[3]
You can use the os
module to execute shell commands.
To clear the terminal, command required in windows is cls
and for unix its clear
import os
os.system('cls' if os.name == 'nt' else 'clear')
If you don't want to clear previous terminal outputs you can use flexibility of print function or the carriage return as others denoted.
for _ in range(3):
print('.', end='')
time.sleep(1)
Solution 4:[4]
If you specifically want to print .
then ..
then ...
, you don't need to remove the existing text; you can just print additional dots.
To make the dots actually appear one by one, you'll need to flush the buffers, using flush=True
import time
for _ in range(3):
print('.', end='', flush=True)
time.sleep(1)
print()
This has the advantage that it will work much more generally; almost any output method can do that, whereas ANSI codes or tricks with \r
or clearing the screen depend on your hardware, operating system and various other things.
Solution 5:[5]
You can do it with ANSI escape codes, like this:
import sys, time
clear_line = '\x1b[1K\r'
print("lol", end="")
sys.stdout.flush() # to force printing the text above
time.sleep(1)
print(clear_line+"test") # Now lol replaced with test
Please note that ANSI codes you should use depend on the environment where the program is executing (platform, terminal, etc.).
Update: you may want to see the built-in curses module.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | L.Grozinger |
Solution 2 | yannvm |
Solution 3 | |
Solution 4 | |
Solution 5 |