Search code examples
python-3.xconsolecommand-line-interfacestdoutpython-curses

Write output in same line, clearing previous line completely on python console


This code demonstrate a progress and print Done... at same console line and exit the program

import time

filename = 'file-name.txt'

for i in range(0, 101):
    time.sleep(0.1)
    print('Downloading File %s [%d%%]\r'% (filename, i), end="", flush=True)

print('Done...\r\n', end="", flush=True)

problem is when program end, it has the remnants of previous line at the end of the last line. bellow output demonstrate a single line updating while program running.

Current Output (Single line update)

Downloading File file-name.txt [1%]
.
.
Downloading File file-name.txt [100%]
Done...ding File file-name.txt [100%]

Expected Output (Single line update)

Downloading File file-name.txt [1%]
.
.
Downloading File file-name.txt [100%]
Done...

Found the same problem in here but it doesn't solve this issue. How can I achieve Expected Output without the remnant of previous line. I guess adding '\b\b\b\b\b\b\b\b\b\b' is not very pythonic


Solution

  • This none printable character \x1b[2K erase current line and fixed the problem.

    import time
    
    filename = 'file-name.txt'
    
    for i in range(0, 101):
        time.sleep(0.1)
        print('Downloading File %s [%d%%]\r'% (filename, i), end="", flush=True)
    
    print('\x1b[2K', end="")
    print('Done...\r\n', end="", flush=True)