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

Mary-Kate Olsen
Release: 2024-11-15 00:35:02
Original
896 people have browsed it

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!'
Copy after login

Produces the following output:

1784  KB / KB 1829 downloaded!
1788  KB / KB 1829 downloaded!
Copy after login

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')
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template