Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relocate file backwards multiple lines (python)

Tags:

python

seek

I am using Python to read a file of the following format:

iter1
iter2
iter3
[n lines of stuff]
FLAG = value

iter1
iter2
iter3
iter4
iter5
[n lines of stuff]
FLAG = value
etc....

I want to to search for FLAG, read that value, and then rewind back by 'n' lines and read the value of the final iteration. Note that there are not always the same number of iterations. The number of lines 'n' is consistent within each file; however, these lines may contain different numbers of bytes so I am having trouble using the seek feature.

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  
like image 790
scobo Avatar asked Jan 23 '26 13:01

scobo


1 Answers

Assuming your "n lines of stuff" don't contain any lines starting with "iter", you're making the problem much harder than it is. All you need to do is keep track of the last line you saw that started with "iter". Then when you see "FLAG=" you have that data already; no need to "rewind" and look for it.

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

In general, it is simplest to read a file once and remember the bits you'll need later as they go by.

like image 167
kindall Avatar answered Jan 25 '26 02:01

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!