Output to the same line overwriting previous output?
Here's code for Python 3.x:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')
The end=
keyword is what does the work here -- by default, print()
ends in a newline (\n
) character, but this can be replaced with a different string. In this case, ending the line with a carriage return instead returns the cursor to the start of the current line. Thus, there's no need to import the sys
module for this sort of simple usage. print()
actually has a number of keyword arguments which can be used to greatly simplify code.
To use the same code on Python 2.6+, put the following line at the top of the file:
from __future__ import print_function
How to overwrite the previous print to stdout?
Simple Version
One way is to use the carriage return ('\r'
) character to return to the start of the line without advancing to the next line.
Python 3
for x in range(10):
print(x, end='\r')
print()
Python 2.7 forward compatible
from __future__ import print_function
for x in range(10):
print(x, end='\r')
print()
Python 2.7
for x in range(10):
print '{}\r'.format(x),
print
Python 2.0-2.6
for x in range(10):
print '{0}\r'.format(x),
print
In the latter two (Python 2-only) cases, the comma at the end of the print statement tells it not to go to the next line. The last print statement advances to the next line so your prompt won't overwrite your final output.
Line Cleaning
If you can’t guarantee that the new line of text is not shorter than the existing line, then you just need to add a “clear to end of line” escape sequence, '\x1b[1K'
('\x1b'
= ESC):
for x in range(75):
print('*' * (75 - x), x, end='\x1b[1K\r')
print()
Overwriting a line after printing out something
By default, print
adds a newline, '\n'
, after all arguments have been printed, moving you to the next line. Pass it end='\r'
(carriage return) to make it return to the beginning of the current line without advancing to the next line. To be sure output isn't buffered (stdout
is typically line buffered when connected to a terminal), make sure to pass flush=True
to print
as well, for a final result of:
for n in range(101):
timefluc = random.uniform(0, 1.2)
time.sleep(timefluc)
print("{0}%".format(n), end='\r', flush=True)
Note that \r
does not erase the line, so this only works because in your code, each new output is guaranteed to be at least as long as the previous line (and therefore will overwrite the entirety of the last line's data). If you might output a long line, then a short line, you'll need to make sure to pad all outputs with spaces sufficient to match or exceed the length of the longest possible line (without exceeding the terminal width).
Write output in same line, clearing previous line completely on python console
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)
Python 3.8: Overwrite and clear previous shorter line in terminal
I have found a decent work around for this problem. You can just fill the end of the string with white spaces with f strings. The full code for the problem I stated in the question would then be:
print('Tessst', end='\r')
print(f'{"Test" : <10}')
I found this way here
Python overwrite a line with another specified line
You can use ANSI escape sequences, as long as your terminal supports them (this is the case on Linux, I'm not sure about Windows)
In particular, the interesting ones for this problem are:
\033[<N>A
- Move the cursor up N lines\033[<N>B
- Move the cursor down N lines
You can print the first two lines normally, then for the third one move up 2 lines, print it (this will print a newline and move the cursor to the second line), move down 1 line and continue with your code. I interted some delays in the code so that the effect is visible:
print("Overwrite this line")
time.sleep(1)
print("I do not want to overwrite any line")
time.sleep(1)
print("\033[2AI want to overwrite the first line\033[1B")
Related Topics
Get Class Labels from Keras Functional Model
How to Fix "Webdriverexception: Message: Connection Refused"
Python: Random Selection Per Group
How to Switch Columns Rows in a Pandas Dataframe
Why Doesn't 2._Add_(3) Work in Python
Python: Read Lines from Compressed Text Files
Find the Division Remainder of a Number
Matching Any Character Including Newlines in a Python Regex Subexpression, Not Globally
Catch Exception and Continue Try Block in Python
Split an Integer into Digits to Compute an Isbn Checksum
Conditionally Format Python Pandas Cell
Anyone Know of a Good Python Based Web Crawler That I Could Use
Python: Use MySQLdb to Import a MySQL Table as a Dictionary