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

Wei Wu picture Wei Wu · Jan 25, 2018 · Viewed 33.2k times · Source

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)):
            if i >= start and i <= end:
                print("line #: %s" % i)
                for i in tqdm(range(0, line_size, batch_size)):
                    # pause if find a file naed pause at the currend dir
                    re_batch = {}
                    for j in range(batch_size):
                        re_batch[j] = re.search(line, last_span)

what's the right way to use tqdm here?

Answer

Valentino Constantinou picture Valentino Constantinou · Mar 14, 2018

You're on the right track. You're using tqdm correctly, but stop short of printing each line inside the loop when using tqdm. You'll also want to use tqdm on your first for loop and not on others, like so:

with open(file_path, 'r') as f:
    for i, line in enumerate(tqdm(f)):
        if i >= start and i <= end:
            for i in range(0, line_size, batch_size):
                # pause if find a file naed pause at the currend dir
                re_batch = {}
                for j in range(batch_size):
                    re_batch[j] = re.search(line, last_span)

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