Print to the same line and not a new line? Print to the same line and not a new line? python python

Print to the same line and not a new line?


It's called the carriage return, or \r

Use

print i/len(some_list)*100," percent complete         \r",

The comma prevents print from adding a newline. (and the spaces will keep the line clear from prior output)

Also, don't forget to terminate with a print "" to get at least a finalizing newline!


For me, what worked was a combo of Remi's and siriusd's answers:

from __future__ import print_functionimport sysprint(str, end='\r')sys.stdout.flush()


From python 3.x you can do:

print('bla bla', end='')

(which can also be used in Python 2.6 or 2.7 by putting from __future__ import print_function at the top of your script/module)

Python console progressbar example:

import time# status generatordef range_with_status(total):    """ iterate from 0 to total and show progress in console """    n=0    while n<total:        done = '#'*(n+1)        todo = '-'*(total-n-1)        s = '<{0}>'.format(done+todo)        if not todo:            s+='\n'                if n>0:            s = '\r'+s        print(s, end='')        yield n        n+=1# example for use of status generatorfor i in range_with_status(10):    time.sleep(0.1)