[Tutor] Extracting lines in a file
bob gailer
bgailer at gmail.com
Tue Apr 6 15:11:46 CEST 2010
On 4/6/2010 2:16 AM, 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?
Others have offered linecache and seek.
The simplest generic solution is:
lines_to_be_read = []
for lineno, line in enumerate(open(filename)):
if "documentation" in line:
lines_to_be_read.append(lineno + 25)
if lineno in lines_to_be_read:
# process this line
lines_to_be_read.pop(0)
--
Bob Gailer
919-636-4239
Chapel Hill NC
More information about the Tutor
mailing list