Home >Backend Development >Python Tutorial >How to Create a Text Progress Bar in the Terminal Using Block Characters?
Uploading and downloading files from an FTP server can be a time-consuming process, especially for large files. It's helpful to provide users with visual feedback on the progress of such operations. One common way of doing this is to display a progress bar in the terminal.
Text progress bars can be created using simple block characters, such as brackets ([ and ]), hyphens (-), and equal signs (=). These characters can be repeated and combined to create a bar that fills up as the operation progresses.
To maintain previous console output while displaying the progress bar, you can use carriage returns (r) and line feeds (n). The carriage return moves the cursor back to the beginning of the current line, while the line feed advances the cursor to the next line. By using these characters in conjunction with the progress bar, you can update the bar without erasing previous content.
Here's an example of how you can implement a simple progress bar in Python using the above principles:
from time import sleep def print_progress_bar(iteration, total, prefix="", suffix="", decimals=1, length=100, fill="#", print_end="\r"): percent = ("{0:.{1}f}".format(100 * (iteration / float(total)), decimals)) filled_length = int(length * iteration // total) bar = fill * filled_length + "-" * (length - filled_length) print(f"\r{prefix} |{bar}| {percent}% {suffix}", end=print_end) if iteration == total: print() # A sample list of 57 items items = list(range(57)) # Iterate through the list and display the progress bar for i, item in enumerate(items): sleep(0.1) print_progress_bar(i + 1, len(items), prefix="Progress:", suffix="Complete", length=50)
The above example is just a basic implementation, and you can customize the progress bar to suit your needs. For instance, you can change the characters used to create the bar, its length, or the number of decimal places displayed in the percentage. You can also add a prefix or suffix to provide additional information about the operation.
By following these principles, you can easily create a text progress bar in your console applications to provide users with visual feedback on their progress.
The above is the detailed content of How to Create a Text Progress Bar in the Terminal Using Block Characters?. For more information, please follow other related articles on the PHP Chinese website!