显示找到的文件数和进度

him*_*mes 5 python

我目前有一个按关键字搜索文件的代码.有没有办法显示找到的文件数,因为代码运行和/或显示进度?我有一个大的目录要搜索,如果可能的话希望看到进展.我目前拥有的代码没有显示太多信息或处理时间.

import os
import shutil
import time
import sys

def update_progress_bar():
  print '\b.',
  sys.stdout.flush()

print 'Starting ',
sys.stdout.flush()

path = '//server/users/'
keyword = 'monthly report'

for root, dirs, files in os.walk(path):
  for name in files:
     if keyword in name.lower():
        time.sleep(0)
        update_progress_bar()

print ' Done!'
Run Code Online (Sandbox Code Playgroud)

2rs*_*2ts 0

这很简单,但为什么不只保留一个计数器呢?

files_found = 0
for root, dirs, files in os.walk(path):
  for name in files:
     if keyword in name.lower():
        files_found += 1
        time.sleep(0)
        update_progress_bar()

print "Found {}".format(files_found)
Run Code Online (Sandbox Code Playgroud)

编辑:如果您想计算进度,您应该首先计算出要迭代的文件数量。files如果您使用嵌套列表理解,您可以展平发出的每个三元组中的每个os.walk

filenames = [name for file in [files for _, _, files in os.walk(path)]]
num_files = float(len(filenames))
Run Code Online (Sandbox Code Playgroud)

现在,在每个步骤中,您可以将进度描述为当前步骤号除以文件数。换句话说,使用enumerate来获取步骤号:

files_found = 0
for step, name in enumerate(filenames):
  progress = step / num_files
  print "{}% complete".format(progress * 100)
    if keyword in name.lower():
      files_found += 1
      time.sleep(0)
      update_progress_bar()
Run Code Online (Sandbox Code Playgroud)

如果您想在打印进度方面更具创意,那就是另一个问题了。