Casa > H > How To Delete The Last Printed Line In Python Language

How to delete the last printed line in Python language

The cleanest approach, if possible, is to use \r, which goes back to the beginning of the line. Your next print will simply start from where the previous one started.

For example:

  1. >>> import time 
  2. >>> def clock(): 
  3. ... while True: 
  4. ... print(datetime.datetime.now().strftime("%H:%M:%S")) 
  5. ... time.sleep(1) 
  6. ... 
  7. >>> clock() 
  8. 00:11:28 
  9. 00:11:29 
  10. 00:11:30 
  11. 00:11:31 
  12. 00:11:32 
  13. 00:11:33 

which is obviously not what we want. Whereas with \r:

  1. >>> import time 
  2. >>> def clock(): 
  3. ... while True: 
  4. ... print(datetime.datetime.now().strftime("%H:%M:%S"), end="\r") 
  5. ... time.sleep(1) 
  6. ... 
main-qimg-3f931976e3eb5d42c7dbd5b48fcf71b2

which is much better.

If you can’t use this approach, you can define:

  1. CURSOR_UP_ONE = '\x1b[1A' 
  2. ERASE_LINE = '\x1b[2K' 

and use them by calling sys.stdout.write.

  1. import sys 
  2. sys.stdout.write(CURSOR_UP_ONE) 
  3. sys.stdout.write(ERASE_LINE) 

If you’re using it a lot, you can define your own function:

  1. def delete_last_lines(n=1): 
  2. for _ in range(n): 
  3. sys.stdout.write(CURSOR_UP_ONE) 
  4. sys.stdout.write(ERASE_LINE) 

De Sirois

Porque é que os telefones já não têm pilhas amovíveis? Qual é melhor, uma bateria removível ou uma não removível? :: Como desbloquear canais codificados no meu descodificador gratuito DVB T2