Display the number of files found and progress

I currently have code that searches for files by keywords. Is there a way to show the number of files found when the code runs and / or shows progress? I have a large directory to search and would like to see progress, if possible. The code I have now does not show much information or processing time.

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!' 
+5
source share
1 answer

It's pretty simple, but why not just keep the counter?

 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) 

Edit: if you want to calculate the progress, you must first find out how many files you will be sorting through. If you use the understanding of a nested list, you can flatten each of the files from each triple emitted by os.walk .

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

Now at each step you can describe the progress as the current step number divided by the number of files. In other words, using enumerate to get the step number:

 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() 

If you want more creativity in the way you print progress arising in another question.

0
source

Source: https://habr.com/ru/post/1262059/


All Articles