Paul Kocian
Paul Kocian

Reputation: 529

How can I delete printed line in python?

I would love to print a counting down and in each second delete a line:

import time
for x in range(3):
    print(x)
    time.sleep(1)
    #Delete previous line

How can I do? Thanks

Upvotes: 1

Views: 2188

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195428

It all depends what terminal are you using. You can simulate the deletion of the line with carriage-return characters \r and spaces ' ', for example:

import time

for x in range(3):
    print(x, end='', flush=True)
    time.sleep(1)
    print('\r    \r', end='', flush=True)

For more advanced solution, look at the curses module.

Upvotes: 2

Related Questions