[Tutor] Extracting lines in a file

Alan Gauld alan.gauld at btinternet.com
Tue Apr 6 09:54:37 CEST 2010

"ranjan das" <ranjand2005 at gmail.com> wrote

> For instance lets say the unique string is "documentation" (and
> "documentation" occurs more than once in the file). Now, on each instance
> that the string "documentation" occurs in the file,  I want to read the 
> 25th
> line (from the line in which the string "documentation" occurs)
> Is there a goto kind of function in python?

There is a seek() function but it would require the lines to be of
constant length. Its probably easier to just use a loop:

def file_jump(fileobj, n =1):
      for line in range(n):

That will move the file pointer forward n lines.

Note, if the jumps can overlap the original then you might want
to  use tell() before the jump to store the original location then
use seek() to go back. (eg if the trigger was in line 5 and the
jump was 7 lines but  the trigger also occured in line 10)


for line in file:
     if trigger in line:
         marker = file.tell()
         file_jump(file, jumps[trigger])
         file.seek(marker)   # go back to original position


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list