Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python-打印文件中最后匹配的行_Python_Python 2.7 - Fatal编程技术网

python-打印文件中最后匹配的行

python-打印文件中最后匹配的行,python,python-2.7,Python,Python 2.7,我正在从Windows服务器上读取各种日志,我正在抓取文件夹中的最新日志 然后我想扫描日志,只打印最后一行,其中包含一个特定的字符串 以下内容将打印包含字符串的所有行- def read_logfile(master_log): for line in master_log: if line.contains('[76:Health]:'): print line 如何让它只打印找到的最后一个匹配项?简单的方法是每次点击时存储,并在循环外打印:

我正在从Windows服务器上读取各种日志,我正在抓取文件夹中的最新日志

然后我想扫描日志,只打印最后一行,其中包含一个特定的字符串

以下内容将打印包含字符串的所有行-

def read_logfile(master_log):
    for line in master_log:
        if line.contains('[76:Health]:'):
            print line

如何让它只打印找到的最后一个匹配项?

简单的方法是每次点击时存储,并在循环外打印:

def read_logfile(master_log):
    lastmatch = None
    for line in master_log:
        if '[76:Health]:' in line:
            lastmatch = line
    if lastmatch is not None:
        print lastmatch
您可以使用带有适当maxlen的a来概括最后n个匹配项,因此您只需在执行过程中附加所有匹配项,一旦超出限制,就会将最早的匹配项推出。下面的工作原理与上面的代码相同,但允许第二个参数打印更多行:

from collections import deque

def read_logfile(master_log, linecount=1):
    lastmatches = deque(maxlen=linecount)
    for line in master_log:
        if '[76:Health]:' in line:
            lastmatches.append(line)
    for line in lastmatches:
        print line

将其存储在数组中,然后打印数组中的最后一项。可以使用pop将行作为str返回


您可以按相反的顺序迭代文件

for line in reversed(master_log.readlines()):
    if '[76:Health]:' in line:
        print(line)
        break

如果你的文件很小,读入它不会有问题。如果它很大,请选择另一个解决方案。

第一个选项非常有效,但我应该意识到python没有字符串。如果“[76:Health]:”在第行:@WhoiseEarth:Oops,我应该自己抓住它。:-我将为未来的读者确定答案。
for line in reversed(master_log.readlines()):
    if '[76:Health]:' in line:
        print(line)
        break