如何在自动更新的文件中获取文本的最后一次出现 - python?

时间:2015-12-05 16:12:23

标签: python

[问题]

在使用新数据自动刷新的文件中,我希望得到: - 与最新字符串occcurence对应的数字。 例如,在上面的虚拟示例中,我想要获取: - stringZ 的最后一次出现以及之后该文本中的数字。 实际上我想要获取:[99]

File sample:    
    "....
    Manually launch test 1 stringX
    Manually launch test 2 stringY
    Manually launch test 3 stringW
    Manually launch test 10 stringZ
    ................
    Manually launch test 200 stringX
    Manually launch test 300 stringY
    Manually launch test 77 stringW
    Manually launch test 99 stringZ
    "

[CODE]

tempFile = open(fileName, "r")
while True:
    fileContent = str(tempFile.readlines())
    print temp
    latestOccurence= re.search("(.*)stringZ",fileContent ).group(0)
    latestOccurence= re.search('([0-9])+',latestOccurence).group(0)
    print latestOccurence

1 个答案:

答案 0 :(得分:0)

regex = re.compile(r'Manually launch test ([0-9]+) stringZ')
while True:
    latestOccurrence = None
    with open(fileName) as tempFile:
        for line in tempFile:
            if "stringZ" in line:
                match = regex.match(line)
                if match:
                    latestOccurrence = int(match.group(1))
    # do something with latestOccurrence here?
    time.sleep(1)