Search code examples
pythonpython-2.7timecountdown

How can I remove last printed line in python?


I'm trying to make countdown program with python. I want to turn that into it removes last printed line, so i can print new second.

import time

def countdown():
    minute = 60
    while minute >= 0:
        m, s = divmod(minute, 60)
        time_left = str(m).zfill(2) + ':' + str(s).zfill(2)
        print(time_left)
        time.sleep(1) 
        minute -= 1

countdown()

I am running python 2.7.13 on Raspberry Pi.


Solution

  • Try the following (it's made in python2):

    import time, sys
    
    def countdown(totalTime):
        try:
            while totalTime >= 0:
                mins, secs = divmod(totalTime, 60)
                sys.stdout.write("\rWaiting for {:02d}:{:02d}  minutes...".format(mins, secs))
                sys.stdout.flush()
                time.sleep(1)
                totalTime -= 1
                if totalTime <= -1:
                    print "\n"
                    break
        except KeyboardInterrupt:
            exit("\n^C Detected!\nExiting...")
    

    Call it like this: countdown(time) For example: countdown(600) for 10 minutes.