Search code examples
pythonpython-2.7stdoutcarriage-return

sys.stdout.write and \r carriage return not working


I was following a little tutorial and after much research, I can't figure out why the given code doesn't print on the same line. I copied it directly, so it should work.

import time
import sys
sys.stdout.write('29 seconds remaining')
time.sleep(1)
sys.stdout.write('\r28 seconds remaining')

Output is:

29 seconds remaining
28 seconds remaining

Final output should be:

28 seconds remaining

Solution

  • I put the "\r" at the end of the line, not at the front. Like this:

     sys.stdout.write("%s[%s%s] %2i/%i\r" % (variables go here))
     sys.stdout.flush()