How to write a code for a progress bar in Python?

Here is a simple example of a Python progress bar code:

import time

def progress_bar(total, current, length=50):
    percent = current/total
    arrow = '#' * int(length * percent)
    spaces = ' ' * (length - len(arrow))
    print(f'[{arrow}{spaces}] {int(percent*100)}%', end='\r')

# 示例用法
total = 100
for i in range(total+1):
    progress_bar(total, i)
    time.sleep(0.1)

In this example, the progress_bar function takes three parameters: total for the total amount, current for the current progress, and length for the length of the progress bar, which defaults to 50. This function calculates the percentage based on the current progress and generates a progress bar of the appropriate length. It then uses the \r to overwrite the output on the same line, making the progress bar dynamically update.

In the example usage, we simulated a process that progresses from 0% to 100%, waiting 0.1 seconds every time the progress bar is updated to observe the effects.

bannerAds