Home  >  Article  >  Backend Development  >  How to Print Continuous Output on a Single Line in Python?

How to Print Continuous Output on a Single Line in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-15 00:35:02897browse

How to Print Continuous Output on a Single Line in Python?

Printing Continuous Output on Single Line

The goal of this question is to output text to a single line, overwriting previous output, creating a real-time progress bar. The code in question:

print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!'

Produces the following output:

1784  KB / KB 1829 downloaded!
1788  KB / KB 1829 downloaded!

To achieve continuous output on the same line, Python provides a simple solution. Here's the modified code using the end keyword:

print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')

The end keyword specifies the character to place at the end of the printed line. By default, print() ends with a newline character (n), which causes the cursor to move to the next line. However, using end='r' instead inserts a carriage return character, returning the cursor to the start of the current line.

This allows for continuous output without the need to import the sys module. Python's print() function offers numerous other keyword arguments that can simplify coding tasks, such as flush and file.

The above is the detailed content of How to Print Continuous Output on a Single Line in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn