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:
- >>> import time
- >>> def clock():
- ... while True:
- ... print(datetime.datetime.now().strftime("%H:%M:%S"))
- ... time.sleep(1)
- ...
- >>> clock()
- 00:11:28
- 00:11:29
- 00:11:30
- 00:11:31
- 00:11:32
- 00:11:33
which is obviously not what we want. Whereas with \r:
- >>> import time
- >>> def clock():
- ... while True:
- ... print(datetime.datetime.now().strftime("%H:%M:%S"), end="\r")
- ... time.sleep(1)
- ...
which is much better.
If you can’t use this approach, you can define:
- CURSOR_UP_ONE = '\x1b[1A'
- ERASE_LINE = '\x1b[2K'
and use them by calling sys.stdout.write.
- import sys
- sys.stdout.write(CURSOR_UP_ONE)
- sys.stdout.write(ERASE_LINE)
If you’re using it a lot, you can define your own function:
- def delete_last_lines(n=1):
- for _ in range(n):
- sys.stdout.write(CURSOR_UP_ONE)
- sys.stdout.write(ERASE_LINE)