Powered by Python: find files whose name contain a criteria string

from os import walk
from os.path import join, getsize
import datetime
import sys
import os
import re

def parse(path, substr="boost"):
    """ this function take a valid directory path as input
    walk through all files and directories and output all 
    matches into log.txt

    logfile = path + r'\log.txt'
    print "Going through %s to find \'%s\'(case insensitive), \nsubdirectory included..."%(path, substr)
    print "a log will be saved to %s"%logfile
    f = open(logfile, 'a') # open a log file
    sys.stdout = f   # un-comment this line out if the output to a file is preferred 

    now = datetime.datetime.now()
    print "\n***********************************************"
    print "\nTimestamp: %s"%now.strftime("%y-%m-%d, %H:%M:%S")

    totalCount = 0
    substr_upper = substr.upper()
    for root,dirs, files in walk(path):
        for file in files:
            if substr_upper in file.upper():
                fullpath = join(root,file)
                print "File #%d: %s"%(totalCount,fullpath)
            #print root, "|", dirs, "|",files
            totalCount += 1
    print "Totally %d files/directories under %s have been searched"%(totalCount, path)
    print r'********* The End *********'

def main():
    from timeit import Timer
    if not len(sys.argv)== 2:
        print "usage: %s [directory, e.g. c:\]" %os.path.basename(sys.argv[0])
        #raw_input('press <Enter> to continue...')    
        #t = Timer("parse(sys.argv[1])", "from __main__ import parse")
        #t.repeat(3, 1000)    #.timeit()    

if __name__ == '__main__': main()

Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: