Move file back multiple lines (python)

I use Python to read a file in the following format:

Iter1
iter2
iter3
[n lines of material]
FLAG = value

Iter1
iter2
iter3
iter4
iter5
[n lines of material]
FLAG = value
, etc.

I want to find the FLAG, read this value, and then rewind to the lines 'n' and read the value of the last iteration. Note that the number of iterations is not always the same. The number of lines "n" is consistent in each file; however, these lines may contain a different number of bytes, so I am having problems using the search function.

I would like to do something like this:

f = open(file)  
for i in f:  
    a = re.search('FLAG')  
    if a:  
          print a  
          spot=f.tell() #mark original spot  
          f.seek(-n,1)  #rewind by n lines  
          b = re.search('iter')  
          print b  
          f.seek(spot) #return to FLAG line, continue to next data set  
+3
2

, "n " ​​ , "iter", , . , , , , "iter". , "FLAG =", ; "" .

lastiterline = None
with open(filename) as f:
    for line in f:
        line = line.strip()
        if line.startswith("iter"):
           lastiterline = line
        elif line.startswith("FLAG"):
           if lastiterline:
               print line
               print lastiterline
           lastiterline = None

, , , .

+1

:

def flagblocks(filename):
    with open(filename) as f:
        yieldlist = []
        for line in f:
            if not line.strip():
                continue
            if not line.startswith("FLAG"):
                yieldlist.append(line)
                continue
            yield yieldlist
            yieldlist = []
         yield yieldlist


for flagblock in flagblocks("filename"):
    process_flagblock_lines(flagblock)

- , .

flagblocks .

0
source

All Articles