2013-04-09 24 views
1

這是我第一次在這裏發佈,我只是在學習python,所以請耐心等待。 我已經在這裏和其他地方在線試圖找到一個答案這個很好看,但唉,網絡似乎bereft!用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

如果您還可以發佈一個示例日誌文件(幾行),並且如果您在繼續獲得某些結果時擴展該示例的擴展,那麼最好。好的開始是在'rU'模式下打開你的文件('U'代表通用行結尾),當你使用''line'.strip(os.linesep)去掉'' – catalesia 2013-04-09 10:06:58

回答

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聲明會結束該功能。

+0

'newb獎給我!非常感謝Manishearth。 – 2013-04-09 10:13:30

+0

@BobHoward:別擔心,我們現在都這樣搞砸了。你不知道'return'(在這種情況下,_learn_!!)。或者你做了,你只是忘了(發生在我身上一百萬次)。只是沉浸在:) – Manishearth 2013-04-09 10:14:54

相關問題