The print()
function has a really useful argument called end
, which allows you to customize the text at the end of print and the placement of the cursor after print. For example, you can use end='\r'
to print the text on same line multiple times, which is really useful to create progress bar's and % complete statements.
But how do I reset the cursor back to a new-line after setting it to the beginning? For example, the following code:
import datetime
start_time = datetime.datetime.now()
sampleRange = range(10)
for i in range(10):
i=i+1
percentComplete = str(i/len(sampleRange)*100)
print(percentComplete + "% done", end="\r")
if i==5:
timeTaken = str(datetime.datetime.now() - start_time)
print(str(i) + "loops done in " + timeTaken)
results in an output:
5loops done in 0:00:00.001001
100.0% done
But the expected output is:
50% done
5loops done in 0:00:00.001001
100.0% done
This helps in adding milestones to a progress bar when necessary.