32

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?

kevlar1818
  • 3,055
  • 6
  • 29
  • 43
  • `sys.stdout.write()` works for me .. you have `import sys`. Are you trying to overlay the output on the same line? – Levon Jun 13 '12 at 15:26
  • If you are trying to get the same effect as `print text,` from python 2.x, you need to use the `end` argument, as in `print(text, end='')`. The comma at the end of the function arguments has no effect. – James Jun 13 '12 at 16:16
  • 2
    Not sure about "from 2.x". The line `print(text, end='')` gives me a syntax error at the `=`. – rossmcm Feb 08 '18 at 22:16

3 Answers3

41

If you want to overwrite your last line you need to add \r (character return) and end="" so that you do not go to the next line.

values = range(0, 100)
for i in values:
    print ("\rComplete: ", i, "%", end="")
print ("\rComplete: 100%")
Joris
  • 540
  • 4
  • 6
32

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.

senderle
  • 145,869
  • 36
  • 209
  • 233
15

I prefer to use the solution of Jan but in this way:

values = range(0, 101)
for i in values:
  print ("Complete: ", i, "%", end="\r")
print ()
Southernal
  • 171
  • 1
  • 5