python: print using carriage return and comma not working

kevlar1818 picture kevlar1818 · Jun 13, 2012 · Viewed 59.8k times · Source

I need to print over one line in a loop (Python 3.x). Looking around on SO already, I put this line in my code:

print('{0} imported\r'.format(tot),)

However, it still prints multiple lines when looped through. I have also tried

sys.stdout.write('{0} imported\r'.format(tot))

but this doesn't print anything to the console...

Anyone know what's going on with this?

Answer

senderle picture senderle · Jun 13, 2012

In the first case, some systems will treat \r as a newline. In the second case, you didn't flush the line. Try this:

sys.stdout.write('{0} imported\r'.format(tot))
sys.stdout.flush()

Flushing the line isn't necessary on all systems either, as Levon reminds me -- but it's generally a good idea when using \r this way.