Is there a way to clear your printed text in python?

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

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

import os
os.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 os
os.system('cls' if os.name == 'nt' else "printf '\033c'")

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

def delete_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()
####################################

Tags:

Python