Skip to content Skip to sidebar Skip to footer

Is There A Way To Clear Your Printed Text In Python?

I have wanted for a long time to find out how to clear something like print('example') in python, but I cant seem to find anyway or figure anything out. print('Hey') >Hey Now I

Solution 1:

import osos.system('cls')

Or os.system('clear') on unix (mac and linux). If you don't want the scroll up either, then you can do this:

os.system("printf '\033c'") should get rid of scroll back too. Something that works on all systems:

import osos.system('cls'ifos.name == 'nt'else"printf '\033c'")

Solution 2:

I think this is what you want to do:

take the cursor one line up and delete the line

this can be done like using the code below

import sys
import time

defdelete_last_line():
    "Use this function to delete the last line in the STDOUT"#cursor up one line
    sys.stdout.write('\x1b[1A')

    #delete last line
    sys.stdout.write('\x1b[2K')


########## FOR DEMO ################if __name__ == "__main__":
    print("hello")
    print("this line will be delete after 2 seconds")
    time.sleep(2)
    delete_last_line()
####################################

Solution 3:

Small addition into @Aniket Navlur 's answer in order to delete multiple lines:

defdelete_multiple_lines(n=1):
    """Delete the last line in the STDOUT."""for _ inrange(n):
        sys.stdout.write("\x1b[1A")  # cursor up one line
        sys.stdout.write("\x1b[2K")  # delete the last line

Solution 4:

Well I have a temporary way:

print("Hey", end="")
for i inrange(4):
    print('\b', end = '')

print("How is your day?")

Solution 5:

The escape character \r (carriage return), means "start printing from beginning of this line". But some of operating systems use it as 'newline'. Following would work in Linux:

import time
import sys
#first text
print('Hey.', end="")
#flushstdout
sys.stdout.flush()
#wait a second
time.sleep(1)
#write a carriage returnand new text
print('\rHow is your day?') 

Post a Comment for "Is There A Way To Clear Your Printed Text In Python?"