多文件,多目录下查询关键字脚本

python脚本作用:目录下有很多的文件,或者存在二级甚至三级目录,我们需要查文件当中的某一个关键字。

import os
import re
import sys


def listFiles(dirPath):
    fileList = [];
    for root, dirs, files in os.walk(dirPath):
        for fileObj in files:
            fileList.append(os.path.join(root,fileObj))
    return fileList

def findString(filePath, regex):
    f=open('rfi_basic.txt','a')
    fileObj = open(filePath, 'r')
    for eachLine in fileObj:
        if re.search(regex, eachLine, re.I):
            f.write(eachLine)        
            #print eachLine
            

            

def main():
    reload(sys)
    sys.setdefaultencoding('utf-8')
    fileDir = "g:"+os.sep+"ips"  //此处填写目录,os.sep表示/
    fileList = listFiles(fileDir)    
    print fileList
    for fileObj in fileList:
        findString(fileObj, ur"查找的关键字")//此处填写要查找的关键字,不区分大小写,可自行修改
#        f.close()
#        os.system("pause")

if __name__ == '__main__':
    main()

 

posted @ 2016-06-27 16:27  lcamry  阅读(389)  评论(0编辑  收藏  举报