How to replace string from previous line using \r (Python) -


this question has answer here:

i'm attempting make countdown timer starting 60 seconds. problem when run function, program prints code so:

60

59

58

... etc

how go replacing 60 first line , put 59 in it's place without printing 60 lines?

here's code:

from __future__ import division import sys, time   def countdown():     seconds = 60     while seconds >= 0:         print seconds         sys.stdout.flush()         time.sleep(1)         seconds -= 1 

print empty line @ beginning of countdown function. create line needed \r work. now, replace print seconds part with

sys.stdout.write('\r  \r') sys.stdout.write(str(seconds)) 

the first line clears previous, empty line printed @ beginning of function. second 1 outputs seconds.

the code:

def countdown():     seconds = 60     print ''     while seconds >= 0:         sys.stdout.write('\r  \r')         sys.stdout.write(str(seconds))         sys.stdout.flush()         time.sleep(1)         seconds -= 1 

Comments