How to rewrite multiple lines in the console with Python?

Sometimes, we want to rewrite multiple lines in the console with Python.

In this article, we’ll look at how to rewrite multiple lines in the console with Python.

How to rewrite multiple lines in the console with Python?

To rewrite multiple lines in the console with Python, we can use sys.stdout.write to move up the cursor to delete a line.

For instance, we write:

import sys
import time
from collections import deque

queue = deque([], 3)
for t in range(20):
    time.sleep(0.5)
    s = "update %d" % t
    for _ in range(len(queue)):
        sys.stdout.write("x1b[1Ax1b[2K")
    queue.append(s)
    for i in range(len(queue)):
        sys.stdout.write(queue[i] + "n")

We have a for loop and we loop from 0 to 19.

In the loop, we call time.sleep to pause for 0.5 seconds.

Then we loop through from 0 to the length of the queue minus 1 with another for loop and erase the previous line by writing:

sys.stdout.write("x1b[1Ax1b[2K")

Next, we call queue.append to append the s string.

And then we call sys.stdout.write(queue[i] + "n") to update the text again.

Conclusion

To rewrite multiple lines in the console with Python, we can use sys.stdout.write to move up the cursor to delete a line.