首頁 >後端開發 >Python教學 >如何在 Python 中列印單行連續輸出?

如何在 Python 中列印單行連續輸出?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 00:35:02936瀏覽

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.

以上是如何在 Python 中列印單行連續輸出?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn