Search code examples
pythonansi-escape

Python overwrite a line with another specified line


How can I overwrite already printed text to STDOUT with an arbitrary string? For example:

print("Overwrite this line")
print("I do not want to overwrite any line")
print("I want to overwrite the first line")

How can I overwrite the first print statement with the third print statement? The second line should remain as it is.


Solution

  • You can use ANSI escape sequences, as long as your terminal supports them (this is the case on Linux, I'm not sure about Windows)

    In particular, the interesting ones for this problem are:

    • \033[<N>A - Move the cursor up N lines
    • \033[<N>B - Move the cursor down N lines

    You can print the first two lines normally, then for the third one move up 2 lines, print it (this will print a newline and move the cursor to the second line), move down 1 line and continue with your code. I interted some delays in the code so that the effect is visible:

    print("Overwrite this line")
    time.sleep(1)
    print("I do not want to overwrite any line")
    time.sleep(1)
    print("\033[2AI want to overwrite the first line\033[1B")