2016-08-01 54 views
0

我有幾百個日誌文件,我需要解析搜索文本字符串。我希望能夠做的是運行一個Python腳本來打開當前文件夾中的每個文件,解析它並將結果記錄到具有original_name_parsed_log_file.txt的新文件中。我有一個腳本在單個文件上工作,但現在我遇到了一些問題,在目錄中執行所有文件。如何解析日誌並提取包含特定文本字符串的行?

下面是我迄今爲止,但它不工作atm。無視第一個def ...我正在玩變化的字體顏色。

import os 
import string 
from ctypes import * 

title = ' Log Parser ' 
windll.Kernel32.GetStdHandle.restype = c_ulong 
h = windll.Kernel32.GetStdHandle(c_ulong(0xfffffff5)) 

def display_title_bar(): 
    windll.Kernel32.SetConsoleTextAttribute(h, 14) 
    print '\n' 
    print '*' * 75 + '\n' 
    windll.Kernel32.SetConsoleTextAttribute(h, 13) 
    print title.center(75, ' ') 
    windll.Kernel32.SetConsoleTextAttribute(h, 14) 
    print '\n' + '*' * 75 + '\n' 
    windll.Kernel32.SetConsoleTextAttribute(h, 11) 

def parse_files(search): 
    for filename in os.listdir(os.getcwd()): 
     newname=join(filename, '0_Parsed_Log_File.txt') 
     with open(filename) as read: 
      read.seek(0) 
      # Search line for values if found append line with spaces replaced by tabs to new file. 
      with open(newname, 'ab') as write: 
       for line in read: 
        for val in search: 
         if val in line: 
          write.write(line.replace(' ', '\t')) 
          line = line[5:] 
      read.close() 
      write.close() 
print'\n\n'+'Parsing Complete.' 
windll.Kernel32.SetConsoleTextAttribute(h, 15) 

display_title_bar() 

search = raw_input('Please enter search terms separated by commas: ').split(',') 
parse_files(search) 
+0

最簡單的方法通過匹配名稱通配符字符串來查找目錄中的文件是使用內置的'glob'模塊。 – PaulMcG

回答

1

此行是錯誤的:

newname=join(filename, '0_Parsed_Log_File.txt') 

使用:

newname= "".join([filename, '0_Parsed_Log_File.txt']) 

join是字符串方法需要一個字符串列表來進行連接,獲取所有

+0

謝謝,這工作。我發佈後,我意識到我已修改該行,並沒有糾正它。這絕對是我的問題的根源。 –

相關問題