Build Python Command-Line Progress Bars with tqdm

Terminal progress bar tracking a Python workflow processing a large collection of files

What You’ll Learn

In this lesson, you will learn how to add a command-line progress bar to a Python script with tqdm. You will use it while processing a collection of files so that you can see how much work has completed and how much remains.

  • Install the tqdm package.
  • Wrap a Python iterable with tqdm().
  • Process multiple files while displaying progress.
  • Understand common mistakes involving imports, paths, and empty collections.
Ad

The Concept

A progress bar is a visual indicator that shows how far a task has progressed. This is especially useful when a script processes many files, downloads data, or performs another operation that takes time.

Python’s built-in for loop does not automatically display progress. The tqdm package adds this feature with very little code. You wrap the iterable you are already looping over:

for file_path in tqdm(file_paths):
    process_file(file_path)

As the loop runs, tqdm updates a progress bar in the terminal. It can show the number of completed items, the total number of items, elapsed time, and an estimated remaining time.

First, install the package from your terminal:

python -m pip install tqdm

The package is named tqdm, and the main function is also named tqdm. Once installed, import it into your Python script with from tqdm import tqdm.

Basic Example

The following script finds text files in an input_files directory. It reads each file, counts its lines, and writes a small report for each file into a reports directory.

from pathlib import Path

from tqdm import tqdm


input_directory = Path("input_files")
report_directory = Path("reports")
report_directory.mkdir(exist_ok=True)

text_files = list(input_directory.glob("*.txt"))

for file_path in tqdm(text_files, desc="Processing files"):
    file_contents = file_path.read_text(encoding="utf-8")
    line_count = len(file_contents.splitlines())

    report_path = report_directory / f"{file_path.stem}_report.txt"
    report_path.write_text(
        f"File: {file_path.name}\n"
        f"Lines: {line_count}\n",
        encoding="utf-8",
    )

print(f"Created {len(text_files)} reports.")

Expected Output

The exact timing and progress-bar appearance depend on your terminal and computer. If the directory contains three text files, the output will look similar to this:

Processing files: 100%|##########| 3/3 [00:00<00:00, 2500.00it/s]
Created 3 reports.

The progress bar may use different symbols, spacing, speed, or timing on your system. The important part is that it moves from 0/3 to 3/3.

How the Code Works

A process diagram showing text files collected from an input directory, wrapped in tqdm, and processed one at a time. After each file is processed, tqdm updates the terminal progress bar. When all files are complete, reports are written and processing finishes.
tqdm wraps the file collection, advances once per processed file, and updates the terminal progress bar until all files are complete.

Path provides convenient tools for working with files and directories. The import makes it possible to represent a path as a Python object instead of manually building strings.

from pathlib import Path

from tqdm import tqdm

The blank line between the imports is a common style choice that separates Python’s standard-library import from the third-party tqdm import.

Next, the script names the input and output directories:

input_directory = Path("input_files")
report_directory = Path("reports")
report_directory.mkdir(exist_ok=True)

mkdir(exist_ok=True) creates the reports directory if it does not exist. If it already exists, the script continues instead of raising an error.

This line collects the files that will be processed:

text_files = list(input_directory.glob("*.txt"))

glob("*.txt") finds files whose names end with .txt directly inside input_files. The result is converted to a list, which gives tqdm a known total number of files.

The key progress-bar line is the loop:

for file_path in tqdm(text_files, desc="Processing files"):

Instead of looping over text_files directly, the code loops over tqdm(text_files). Each time the loop reaches the next file, tqdm updates the terminal display. The desc argument adds a readable label before the bar.

The rest of the loop performs the actual file work:

file_contents = file_path.read_text(encoding="utf-8")
line_count = len(file_contents.splitlines())

report_path = report_directory / f"{file_path.stem}_report.txt"
report_path.write_text(
    f"File: {file_path.name}\n"
    f"Lines: {line_count}\n",
    encoding="utf-8",
)

The file is read as UTF-8 text, and splitlines() creates a list of its lines. The report filename uses file_path.stem, which is the original filename without its extension. For example, notes.txt produces notes_report.txt.

Because the progress bar is based on the collection being iterated over, it works with many kinds of iterables, not only file paths. You can use it with lists, directory results, and other collections.

Another Example

A progress bar can also show progress while inspecting files in nested directories. This example finds every .log file below a directory and calculates the total number of bytes stored in those files.

from pathlib import Path

from tqdm import tqdm


log_directory = Path("application_logs")
log_files = list(log_directory.rglob("*.log"))

total_bytes = 0

for log_path in tqdm(log_files, desc="Measuring log files"):
    total_bytes += log_path.stat().st_size

print(f"Found {len(log_files)} log files.")
print(f"Total size: {total_bytes} bytes.")

Here, rglob("*.log") searches through the directory and its subdirectories. The progress bar still works the same way: it wraps the collection used by the for loop.

Common Mistakes

Forgetting to install tqdm

If Python reports ModuleNotFoundError: No module named 'tqdm', install the package in the environment where you run the script:

python -m pip install tqdm

If you use a virtual environment, activate it before installing the package so that the package is available to that environment.

Forgetting the import

Installing a package does not automatically make its functions available in a script. Include this import:

from tqdm import tqdm

Using the wrong directory

Paths such as input_files are usually relative to the directory from which you start the script. If the progress bar immediately shows 0/0, check that the directory exists in the current working directory and that its files match the pattern, such as *.txt.

Expecting the progress bar to measure work inside one item

In the first example, one progress-bar step represents one file. If one file takes a very long time to process, the bar will not move again until that file finishes. This is normal: the bar is tracking files, not individual lines inside each file.

Try It Yourself

Create an input_files directory and place several text files inside it. Run the basic example, then open the generated files in the reports directory.

Modify the script so that each report also includes the number of characters in the original file. Keep the progress bar wrapped around the collection of files.

Challenge

Write a script that processes all .log files in a logs directory.

  • Display a progress bar labeled Reading log files.
  • Count the number of lines in every log file.
  • Write one combined report to reports/log_summary.txt.
  • Include the filename and line count for each log file.
  • Print the total number of processed files when finished.

Solution

from pathlib import Path

from tqdm import tqdm


log_directory = Path("logs")
report_directory = Path("reports")
report_directory.mkdir(exist_ok=True)

log_files = list(log_directory.glob("*.log"))
summary_lines = []

for log_path in tqdm(log_files, desc="Reading log files"):
    contents = log_path.read_text(encoding="utf-8")
    line_count = len(contents.splitlines())
    summary_lines.append(f"{log_path.name}: {line_count} lines")

summary_path = report_directory / "log_summary.txt"
summary_path.write_text(
    "\n".join(summary_lines) + "\n",
    encoding="utf-8",
)

print(f"Processed {len(log_files)} log files.")
print(f"Summary written to {summary_path}.")

The script first collects the matching log files, then wraps that list with tqdm(). Each loop iteration reads one file and adds its result to summary_lines. After all files have been processed, the collected results are joined and written to one report file.

If there are no matching log files, the loop completes without adding any summary lines, and the script still creates an empty report. The progress bar will show 0/0, which indicates that no files matched the pattern.

Key Takeaways

  • Install tqdm with python -m pip install tqdm.
  • Import the progress-bar function with from tqdm import tqdm.
  • Wrap the iterable in a loop with tqdm(iterable).
  • Use the desc argument to give the progress bar a useful label.
  • The bar tracks iterations, so one progress step represents one item in the iterable.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Ad
Ad
Ad