python 脚本搜索目录下的关键字

本文介绍了一个使用Python编写的简单日志搜索工具,该工具能够遍历指定目录及其子目录下的所有文件,查找预设的关键字,并记录含有这些关键字的文件路径及具体行号。
#!/usr/bin/python  
# coding:utf8  
import os  
import re

import string

key_word_list = [] #关键字列表

xxx_log = os.getcwd() + "/" + 'xxx.log' #保存的日志

# 日志 保存一个文件中

def logToFile(msg):

    try:
        fp = open(search_key_log, 'a+')
    except IOError:
self.warn("[WARNING] " + xxx_log + " can't be created")
fp.close()
return -1
    except Exception as e:
self.warn("General error when opening " +
  xxx_log + " " + str(e))
fp.close()
return -1
    fp.write(msg + "\n")
    fp.close()

    return 1

# 判断文件中是否包含关键字,是则将文件路径打印出来  
def is_file_contain_word(file_list): 
    logFlag = 0
    for _file in file_list:
        try: 
            with open(_file, 'r') as fd:
        count = 0
        for i in range(0, len(key_word_list), 1):
            query_word = key_word_list[i]
            while True:
        line = fd.readline()
        if not line:
            break
        count += 1
                        line = line.strip() 
        if not len(line) or line.startswith('//'):
    continue
        for i in range(0, len(key_word_list), 1):
            query_word = key_word_list[i]
    if query_word in line:
          info = "find keyword:%s , in file:%s, the line number is %d" %(query_word,_file, count)
        logToFile(info)
        logFlag = 1
        except IOError:
            print("%s can not open" %(_file))
    if logFlag == 0:
print("no key words found in this directory")
    else:
        print("Using cat xxx.log to check result at current directory")
    print("Finish searching.")  
    return 1
  
# 返回指定目录的所有文件(包含子目录的文件)  
def get_all_file(floder_path):  
    file_list = []  
    if floder_path is None:  
        raise Exception("floder_path is None")  
    for dirpath, dirnames, filenames in os.walk(floder_path):  
        for name in filenames:  
            file_list.append(dirpath + '/' + name)  
    return file_list  
  
if __name__ == '__main__':  
    basedir = raw_input("Please input the directory:")   
    is_file_contain_word(get_all_file(basedir))  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值