如何解析日志并提取包含特定文本字符串的行?

时间:2016-08-01 15:59:13

标签: python string parsing

我有几百个日志文件,我需要解析搜索文本字符串。我希望能够做的是运行Python脚本来打开当前文件夹中的每个文件,解析它并使用original_name_parsed_log_file.txt将结果记录在一个新文件中。我让脚本处理单个文件,但现在我在编写目录中的所有文件时遇到了一些问题。

以下是我到目前为止所做的,但它没有工作。无视第一个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)

1 个答案:

答案 0 :(得分:1)

这一行错了:

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

使用:

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

join是一个字符串方法,需要加入字符串列表

相关问题