Python自定义搜索日志文件不返回结果

时间:2017-05-02 15:22:19

标签: python windows search text-files logfile

我正在使用此代码尝试为包含关键字的日志文件提取行。但是,我知道包含这些单词的文件和行不会写入新的错误文件。

我原本以为我的问题是因为Windows和Linux之间的终端字符不同但我从这些原始文件中删除了行,因此警告是文件中的第一个单词。这些行仍未添加到错误文件中。

我创建了自己的文件,其中填写了随机文字和“警告”字样。在几个地方,并正确输出。我使用了正则表达式,它们对情况没有影响。一旦我开始工作,我会将其转换为使用正则表达式。

附加示例文件: https://ufile.io/b8gf4

任何帮助都会很棒,甚至可以指向解决方案。

def errorSearch(filename):
    errorfile = "error" + filename
    print(errorfile)
    try:
            fileopen = open(filename, "r")
            errorfileopen = open(errorfile, 'w')
            runtest(fileopen, errorfileopen)

            return 1
    except IOError:
            print ("Error: File does not appear to exist.")
            return 0

def runtest(logfile, error):
    num = 0
    for line in logfile:
            if 'Warning' in line:
                    error.write(line)
                    num+=1
    print(num)


errorSearch("log.txt")

日志文件代码示例适用于复制和粘贴代码,但不适用于原始文本:

Warning event: POST Err Sensor reports DIMM_F1 disabled.                                              BIOS POST - LUN#0 (Channel#0) 
Warning event: POST Err Sensor reports DIMM_F1 failed test/initialization.                            BIOS POST - LUN#0 (Channel#0) 
Warning event: POST Err Sensor reports DIMM_F2 disabled.                                              BIOS POST - LUN#0 (Channel#0) 
Warning event: POST Err Sensor reports DIMM_F2 failed test/initialization.                            BIOS POST - LUN#0 (Channel#0) 
Informational event: BIOS Evt Sensor reports a system boot event has occurred.                        BIOS POST - LUN#0 (Channel#0) 
Informational event: BIOS Evt Sensor reports Timestamp Clock Sync. Event is first of two expected events from BIOS on every power on.                          BIOS POST - LUN#0 (Channel#0) 
Informational event: BIOS Evt Sensor reports Timestamp Clock Sync. Event is second of two expected events from BIOS on every power on.                         BIOS POST - LUN#0 (Channel#0) 
Warning event: POST Err Sensor reports DIMM_F1 disabled.                                              BIOS POST - LUN#0 (Channel#0) 
Warning event: POST Err Sensor reports DIMM_F1 failed test/initialization.                            BIOS POST - LUN#0 (Channel#0) 
Warning event: POST Err Sensor reports DIMM_F2 disabled.                                              BIOS POST - LUN#0 (Channel#0) 
Warning event: POST Err Sensor reports DIMM_F2 failed test/initialization.                            BIOS POST - LUN#0 (Channel#0)

1 个答案:

答案 0 :(得分:1)

只需添加strip命令即可过滤掉可能与if语句混淆的垃圾字符。

length

另外,请记得关闭错过文件句柄。