0

[PROBLEM]

In a File that refreshes automatically with new data, I want to get: - the number that corresponds to latest string occcurence. For instance, in the dummy example below above I want to fetch: - last occurence of stringZ and afterwards the number inside that text. In practical terms I want to fetch: [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
george
  • 685
  • 2
  • 9
  • 22

1 Answers1

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)
wildwilhelm
  • 4,809
  • 1
  • 19
  • 24
  • I think it is not solving the problem that the file can be updated – Paweł Kordowski Dec 05 '15 at 16:23
  • @ wildwilhelm. thanks for suggestion, in the same time it fetches both occurences, namely: 10 and 99. I will keep investigating...... – george Dec 05 '15 at 16:37
  • @user3438538 the code will match all occurrences in the file, but by the time the file is closed (i.e., where the comment "do something ..." is), the variable `latestOccurrence` should contain the last value found. – wildwilhelm Dec 05 '15 at 16:43