Python colorama – Creating a progress bar

In this post we will be creating a progress bar in Python using Colorama. Colorama is a Python library that simplifies the process of adding colors and styles to command-line output. It provides cross-platform support for colored terminal text, making it easier to enhance the visual appearance of terminal text. With Colorama, developers can easily make their terminal output more readable and visually appealing.

See the sample of Python code below where we use the Colorama library to create a progress bar. We start by defining the total number of steps for the progress bar and initialize a variable to keep track of the current step. Using a while loop the script iterates until the current step is equal to the total number of steps. In this example the number of steps is 10. Inside the loop, the code calculates the progress bar as a string of # characters for completed steps and - characters for incomplete steps. This is printed to the console using the print() function, with Colorama codes used to set the color and brightness of the text. The code then waits for half a second using time.sleep() before incrementing the current step and continuing the loop.

Once the loop completes, the code prints a message indicating that the progress is complete, using a green and bright text color. It then waits for 10 seconds before exiting.

import colorama
from colorama import Fore, Style
import time


total_steps = 10
current_step = 0
while current_step < total_steps:
    current_step += 1
    progress = '#' * current_step + '-' * (total_steps - current_step)
    status = f'Progress: {current_step}/{total_steps}'
    print(Fore.BLUE + Style.BRIGHT + progress + ' ' + status, end='\r')

print(Fore.GREEN + Style.BRIGHT + 'Progress complete!')

See an image example below.

Python colorama - Creating a progress bar

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply