pythonprogress-barenumeratetqdm

Python enumerate() tqdm progress-bar when reading a file?


I can't see the tqdm progress bar when I use this code to iterate my opened file:

with open(file_path, 'r') as f:
    for i, line in enumerate(tqdm(f)):
        print("line #: %s" % i)
        for j in tqdm(range(line_size)):
            ...

What's the right way to use tqdm here?


Solution

  • Avoid printing inside the loop when using tqdm. Also, use tqdm only on the first for-loop, and not on the inner for-loop.

    from tqdm import tqdm
    with open(file_path, 'r') as f:
        for i, line in enumerate(tqdm(f)):
            for j in range(line_size):
                ...
    

    Some notes on using enumerate and its usage in tqdm are available here.