使用Python从第二个文件的列表中搜索一个文件

时间:2013-04-09 09:59:15

标签: python search text

这是我第一次在这里发帖,我只是在学习python,所以请耐心等待。 我已经在这里和其他地方好好看了一下,试图找到答案,但是,唉,网络似乎没有了!

我有一个每天生成的日志文件,可能包含许多语法不同的错误。其中一些很重要而另一些则可以忽略不计,但由于它们都包含文本“错误”,我不能只搜索一个单词。

我有一个错误文本列表,这些错误来自之前在一个文件中看到过的错误,我希望将日志文件与匹配项进行比较,以便在看到任何错误时发出警告。

我已经成功解决了一个错误,但我无法让它为列表工作。

有效的代码如下:

    log_file = open ('a file location' , 'r')
    read_file = file.read ()
    search = read_file.find ('Error type 1 happened at x')
    if search != -1:
        print 'Error found in  log at point ' + str((search)) + '!!!'
    else :
        print "All is good!!!  :-D "

对于列表,我尝试了以下内容:

    load_log_file = open ('a file location' , 'r')
    read_log_file = load_log_file.read ()

    def txt_search (read_log_file):
        errors = open ('another file location' , 'r')
    for error in errors.readlines() :
            if error.strip ('\r\n') in read_log_file:
                return 'Error found in log !!!'
            else :
                return "All is good!!!  :-D "

    print txt_search (read_log_file)

我在运行时得到了一个结果,但总是回来时“一切都很好”。 我可能错过了一些非常明显的东西,但是会得到很多帮助。

非常感谢

1 个答案:

答案 0 :(得分:2)

你过早地回来了。

load_log_file = open ('a file location' , 'r')
read_log_file = load_log_file.read ()

def txt_search (read_log_file):
    errors = open ('another file location' , 'r')
    for error in errors.readlines() :
        if error.strip ('\r\n') in read_log_file:
            return 'Error found in log !!!'

    return "All is good!!!  :-D "

print txt_search (read_log_file)

原始代码中发生的是它查找第一个错误,找不到它,然后返回“All is good”。永远记住return语句结束了该功能。