Phyton script for looking files with specific text pattern, in a directory tree.

'''
Hi, This is the minimized version of some more
complicated script I wrote for some project.
What we basically do here is look for some files (with the same name)
with specific text pattern in it. All files with this
"magic" pattern will be opened with notepad.

Created on Feb 14, 2011

@author: feliponcho
'''

import os
import sys

#set some global data here
pattern = "magic pattern"
search_file = "hello.lst"

#define our methods
def parseFile(filePath):
    try: 
        file = open(filePath, 'rb', 1)
    except IOError:
        return ""
    else: 
        file.close() 
        inList = file.readlines()
        magic = "";
        for line in inList:
            if pattern in str(line):
                return filePath
        return magic        
   

def parseFiles(dirList, dirPath, typeList):
    for file in dirList:
        for ext in typeList:
            if file.endswith(ext):
                filePath = dirPath + "\\" + file
                magic = parseFile( filePath )
                if magic != "":
                    openFile( filePath )                    
    
def parseDirectory(dirEntry, typeList):
    parseFiles(dirEntry[2], dirEntry[0], typeList)
    
def openFile(filePath):
   
    notepad = 'c:\\windows\\system32\\notepad.exe'
       
    if os.path.isfile(filePath):
        os.spawnv(os.P_DETACH, notepad, ('notepad.exe',filePath))

#MAIN STARTS HERE!!
#validate parameter
try:
    path = str(sys.argv[1])

except LookupError:
    print( "Invalid argument: supply only the path of the search Folder")
else:
    print("looking for "+search_file+" in "+path)

    #Convert pattern string to list of file extensions
    extList = []
    for ext in pattern.split(";"):
        extList.append(ext.lstrip("*"))
                      
    #Enumerate the entries in the tree
    for directory in os.walk(path):
        parseDirectory(directory, extList)
    
#MAIN ENDS HERE!!