Overwriting a Single Line
To overwrite a single line, use \r (carriage return). This control character moves the cursor to the beginning of the current line.
print("\r" + "Overwriting a single line!", end="")
Use end="" to prevent a newline character from being printed, keeping the cursor on the same line.
Overwriting Multiple Lines
To overwrite multiple lines, you can use special ANSI escape codes. The sequence \033[nA moves the cursor up n lines.
import time
print("First line")
print("Second line")
print("Third line")
time.sleep(1) # Wait for a second to see the initial output
# Move cursor up 2 lines (from the current position, which is after "Third line")
# and then overwrite the second and third lines.
print("\033[2A" + "New Second line\n" + "New Third line")