在Python中遍历大文件并显示进度指示器?

11 投票
5 回答
16304 浏览
提问于 2025-04-18 14:16

我正在处理一个很大的csv文件,想要显示一些进度指示器。根据我的理解,计算行数需要遍历整个文件,查找换行符。所以我不能简单地通过行号来估计进度。

有没有其他方法可以在读取行的时候估计进度呢?也许我可以根据文件大小来判断?

5 个回答

5

你可以使用 os.path.getsize(或者 os.stat)来获取你的文本文件的大小。然后,每当你解析一行新内容时,计算这一行的字节大小,并把它作为一个参考指标。

import os
fileName = r"c:\\somefile.log"
fileSize = os.path.getsize(fileName)

progress = 0
with open(fileName, 'r') as inputFile:
    for line in inputFile:
        progress = progress + len(line)
        progressPercent = (1.0*progress)/fileSize

#in the end, progress == fileSize
6

这段内容是基于@Piotr对Python3的回答。

import os
import tqdm

with tqdm(total=os.path.getsize(filepath)) as pbar:
    with open(filepath) as file:
        for line in file:
            pbar.update(len(line.encode('utf-8')))
            ....
        file.close()
6

请看看这个小而实用的库,叫做 tqdm,你可以在这里找到它 https://github.com/noamraph/tqdm。只需把一个迭代器包裹起来,当你执行循环时,就会显示一个很酷的进度条。

图片说明了一切。

enter image description here

8

你可以使用 os.path.getsize(filename) 来获取你想要的文件大小。然后在你从文件中读取数据的时候,可以用一个简单的公式来计算进度百分比,公式是 当前已读字节数/文件大小*100%。这个计算可以在每读完 N 行后进行一次。

至于实际的进度条,你可以看看这个链接:控制台中的文本进度条

22

你可以用tqdm来处理大文件,方法如下:

import os
import tqdm

with tqdm.tqdm(total=os.path.getsize(filename)) as pbar:
   with open(filename, "rb") as f:
      for l in f:
          pbar.update(len(l))
          ...

如果你读取的是一个utf-8格式的文件,那么用len(l)来计算长度时,得到的字节数可能不完全准确,但这个结果应该是足够用的。

撰写回答