Using tqdm in Python: Installation, Basic Usage, Customization, and Performance Tips
This article introduces the Python tqdm library, covering its installation, basic usage in loops, customization options such as description, length and bar format, a practical file‑download example, and performance tips for efficiently tracking progress in large or long‑running tasks.
Hello everyone, today we share the amazing Python library tqdm.
tqdm provides simple and powerful progress bars for tracking tasks in Python, useful for loops and long-running processes.
GitHub address: https://github.com/tqdm/tqdm
1. Introduction to tqdm
tqdm (short for "taqaddum", meaning "progress") is a Python library that displays progress bars in the terminal, allowing easy tracking of iteration progress.
1.1 Installation
Before using tqdm , ensure it is installed. If not, install via:
pip install tqdm2. Basic Usage Examples
2.1 Using tqdm in a for loop
The most common usage is wrapping any iterable with tqdm() :
from tqdm import tqdm
import time
for i in tqdm(range(10)):
time.sleep(1) # simulate task execution timeThis creates a simple progress bar for 10 tasks.
2.2 Customizing style
tqdm allows customizing length, prefix, suffix, etc.
Example:
from tqdm import tqdm
import time
for i in tqdm(range(10), desc="Processing", ncols=100):
time.sleep(0.5)3. Progress Bar Customization
3.1 Setting description
Use the desc parameter to add a description.
for task in tqdm(tasks, desc="Processing"):
time.sleep(0.5)3.2 Custom length
Use ncols to set bar length.
for task in tqdm(tasks, ncols=100):
time.sleep(0.5)3.3 Changing bar format
Use bar_format to change appearance.
for task in tqdm(tasks, bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt}"):
time.sleep(0.5)4. Practical Example: File Download Progress
Demonstrates using tqdm to show download progress:
import requests
from tqdm import tqdm
# File URL
url = "https://example.com/file.zip"
response = requests.get(url, stream=True)
# Get total size
total_size = int(response.headers.get('content-length', 0))
block_size = 1024 # 1 KiB
with open("file.zip", "wb") as file, tqdm(total=total_size, unit='iB', unit_scale=True) as bar:
for data in response.iter_content(block_size):
file.write(data)
bar.update(len(data))5. Performance Considerations
When handling large data or long-running tasks, tqdm performance may be affected. Tips include adjusting refresh frequency with appropriate tqdm.update calls and using tqdm.write instead of frequent updates.
Top Architecture Tech Stack
Sharing Java and Python tech insights, with occasional practical development tool tips.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.