0

I am trying to mark a specific line to be my 'checkpoint', so that everytime my condition is satisfied, the program will go back to that checkpoint and read lines starting from there. I am unsure of how to do this.

This is my current code, which doesn't solve the problem (In this context, I search for a FLAG followed by a line containing a stock name(stocklist[k] and NysImbClearPrice, then I do something with it and extract that. then I go back to FLAG to read the lines again, this time searching for a line containing a different stock name):

with open('loggerdec7.log', 'r') as rf:
    found = False
    k = 0
    for line in rf:                         
        if 'FLAG' in line:
            spot = rf.tell() #mark specified checkpoint
            found = True
        if found:
            nameandnysimb = [stocklist[k], 'NysImbClearPrice:']
            if all(x in line for x in nameandnysimb):   
                k+=1    
                clearprice = line.split('NysImbClearPrice: ',1)[-1].split(' ',1)[0]
                cplist.append(clearprice)
                rf.seek(spot) #relocate to specified checkpoint
gubith
  • 13
  • 3
  • What exactly is your question? – mkrieger1 Dec 20 '20 at 09:08
  • this is probably doing omething that is better done via regex. you search for a FLAG followed by a line containing NysImbClearPrice then ou do something with it and extract that. then you want to go back to FLAG to read the lines again. Why? – Patrick Artner Dec 20 '20 at 09:20
  • @PatrickArtner this is because the line contains NysImbClearPrice along with the stock name (stocklist[k]), where the stock name is supposed to change in each iteration. I just did not include that list here. – gubith Dec 20 '20 at 10:41
  • @mkrieger1 I want to know how to do what I mentioned in my first line. I believe Patrick Artner's comment describes it more accurately. – gubith Dec 20 '20 at 10:46

2 Answers2

0

I think you can use readlines() method and get the lines in a list. After that you can simply iterate through the list and keep track of the index.

Nikunj Mundhra
  • 123
  • 1
  • 1
  • 6
0

You can try something like this, where i will keep track of the line number:

with open('loggerdec7.log', 'r') as rf:
    lines = rf.read().splitlines()

found = False
for i, line in enumerate(lines):
    if 'FLAG' in line:
        found = True
        break

if found:
    # do something
PApostol
  • 2,152
  • 2
  • 11
  • 21