Jonathan has given quite a good answer which I think would solve your
problem. Here's my take on it. The way of looking at it is a little
different but Jonathan's approach is much simpler.

The problem is that when you do "for line in f" you are using Python's
iterators and they are not rewindable i.e. "for line in f" gives call the
next() function but there is no way to go back when you use iterators. You
can solve your problem with the following snippet of code.

#!/usr/bin/env python

import re
import sys

# not doing input validation
# call program as: python prog.py start_keyword stop_keyword file_to_read
startat = sys.argv[1]
stopat = sys.argv[2]
inputfile = sys.argv[3]

re_startat = re.compile(r'^%s$' % (startat))
re_stopat = re.compile(r'^%s$' % (stopat))
pattern = re_startat

with open(inputfile) as f:
    line = f.readline()
    inrange = False
    while line:
        match = re.search(pattern, line)
        # if the pattern matches
        if (match):
            # and we are not in range of startat - stopat
            if (not inrange):
                # get in range and change the pattern
                inrange = True
                pattern = re_stopat
            else:
                # we are in the range => stopat pattern matched
                # print line and exit
                print line
                break
        if (inrange):
            # we are in range + stopat pattern not matched
            # keep on printing
            print line
        line = f.readline()

It does look prettier in vim on a black screen though :) 

The idea is you are "in range" if you have matched your first keyword and
till you stay in the range you keep on printing. When you find your next
keyword, you are "out of the range"  and you exit. 

Hope that helps.

--
regards,
Saurabh.
http://curiosityhealsthecat.blogspot.in/



--
View this message in context: 
http://python.6.x6.nabble.com/Novice-Question-on-File-seek-and-tell-methods-tp5021174p5021552.html
Sent from the Bangalore (BangPypers) mailing list archive at Nabble.com.
_______________________________________________
BangPypers mailing list
BangPypers@python.org
http://mail.python.org/mailman/listinfo/bangpypers

Reply via email to