[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):
            fileobj.readline()

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)

Pseudocode:

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

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list