[Tutor] Extracting lines in a file

Dave Angel davea at ieee.org
Tue Apr 6 11:26:44 CEST 2010


ranjan das wrote:
> Hi,
>
>
> I am new to python, and specially to file handling.
>
> I need to write a program which reads a unique string in a file and
> corresponding to the unique string, extracts/reads the n-th line (from the
> line in which the unique string occurs).
>
> I say 'n-th line' as I seek a generalized way of doing it.
>
> 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?
>
> Kindly help
>
>   
You can randomly access within an open file with the seek() function.  
However, if the lines are variable length, somebody would have to keep 
track of where each one begins, which is rather a pain.  Possibly worse, 
on Windows, if you've opened the file in text mode, you can't just count 
the characters you get, since 0d0a is converted to 0a before you get 
it.  You can still do it with a combination of seek() and tell(), however.

Three easier possibilities, if any of them applies:

1) If the lines are fixed in size, then just randomly access using 
seek() before the read.

2) If the file isn't terribly big, read it into a list with readlines(), 
and randomly access the list.

3) If the file is organized in "records" (groups of lines), then read 
and process a record at a time, rather than a line at a time.  A record 
might be 30 lines, and if you found something on the first line of the 
record, you want to modify the 26th line (that's your +25).  Anyway, 
it's possible to make a wrapper around file so that you can iterate 
through records, rather than lines.

HTH
DaveA



More information about the Tutor mailing list