python在读取文件时枚举tqdm bar?

Wei*_* Wu 7 python enumerate tqdm

当我使用此代码迭代打开的文件时,我看不到tqdm进度条:

        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)
Run Code Online (Sandbox Code Playgroud)

什么是在这里使用tqdm的正确方法?

小智 16

我也遇到了这个问题 - tqdm没有显示进度条,因为没有提供文件对象中的行数。

for循环将遍历行,读书遇到下一个换行符到。

为了将进度条添加到tqdm,您首先需要扫描文件并计算行数,然后将其传递给 tqdm 作为total

from tqdm import tqdm

num_lines = sum(1 for line in open('myfile.txt','r'))
with open('myfile.txt','r') as f:
    for line in tqdm(f, total=num_lines):
        print(line)
Run Code Online (Sandbox Code Playgroud)


Val*_*nou 14

你走在正确的轨道上.您正确使用tqdm,但在使用tqdm时,请不要在循环内打印每一行.你还想在你的第一个for循环中使用tqdm,而不是在其他循环中使用tqdm,如下所示:

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)
Run Code Online (Sandbox Code Playgroud)

使用的一些注意事项一一列举,它是在tqdm使用这里.


hob*_*obs 6

我试图对包含所有维基百科文章的文件做同样的事情。所以我不想在开始处理之前计算总行数。它也是一个 bz2 压缩文件,所以解压缩行的 len 高估了该迭代中读取的字节数,所以......

with tqdm(total=Path(filepath).stat().st_size) as pbar:
    with bz2.open(filepath) as fin:
        for line in fin:
            pbar.update(fin.tell() - pbar.n)
    
    # used this to figure out the attributes of the pbar instance
    # print(vars(pbar))
Run Code Online (Sandbox Code Playgroud)

感谢Yohan Kuanke删除的答案。如果版主取消删除它,您可以使用我的。


ejk*_*hen 6

如果您正在读取非常大的文件,请尝试以下方法:

from tqdm import tqdm
import os

file_size = os.path.getsize(filename)
lines_read= []
pbar = tqdm.tqdm(total=file_zize, unit="MB")
with open(filename, 'r', encoding='UTF-8') as file:
    while (line := file.readline()):
        lines_read.append(line)
        pbar.update(s.getsizeof(line)-sys.getsizeof('\n'))
pbar.close()
Run Code Online (Sandbox Code Playgroud)

我省略了您在之前可能想做的处理append(line)

编辑:

我更改len(line)s.getsizeof(line)-sys.getsizeof('\n')aslen(line)并不能准确表示实际读取了多少字节(请参阅有关此的其他帖子)。但即使这也不是 100% 准确,因为 sys.getsizeof(line) 不是读取的实际字节长度,但如果文件非常大,它是一个“足够接近”的黑客。

我确实尝试使用 f.tell() 代替,并在 while 循环中减去文件 pos 增量,但使用非二进制文件的 f.tell 在 Python 3.8.10 中非常慢。

根据下面的链接,我还尝试将 f.tell() 与 Python 3.10 一起使用,但这仍然很慢。

如果有人有更好的策略,请随时编辑此答案,但请在编辑之前提供一些性能数据。请记住,对于非常大的文件,在执行循环之前计算行数是不可接受的,并且完全达不到显示进度条的目的(例如,尝试包含 3 亿行的 30Gb 文件)

为什么 f.tell() 在 Python 中以非二进制模式读取文件时速度很慢 https://bugs.python.org/issue11114