iterating over a file with two pointers
nikhil Pandey
nikhilpandey90 at gmail.com
Wed Sep 18 08:14:23 EDT 2013
On Wednesday, September 18, 2013 5:14:10 PM UTC+5:30, Peter Otten wrote:
> nikhil Pandey wrote:
>
>
>
> > hi,
>
> > I want to iterate over the lines of a file and when i find certain lines,
>
> > i need another loop starting from the next of that "CERTAIN" line till a
>
> > few (say 20) lines later. so, basically i need two pointers to lines (one
>
> > for outer loop(for each line in file)) and one for inner loop. How can i
>
> > do that in python? please help. I am stuck up on this.
>
>
>
> Here's an example that prints the three lines following a line containing a
>
> '*':
>
>
>
> Example data:
>
>
>
> $ cat tmp.txt
>
> alpha
>
> *beta
>
> *gamma
>
> delta
>
> epsilon
>
> zeta
>
> *eta
>
>
>
> The python script:
>
>
>
> $ cat tmp.py
>
> from itertools import islice, tee
>
>
>
> with open("tmp.txt") as f:
>
> while True:
>
> for outer in f:
>
> print outer,
>
> if "*" in outer:
>
> f, g = tee(f)
>
> for inner in islice(g, 3):
>
> print " ", inner,
>
> break
>
> else:
>
> break
>
>
>
> The script's output:
>
>
>
> $ python tmp.py
>
> alpha
>
> *beta
>
> *gamma
>
> delta
>
> epsilon
>
> *gamma
>
> delta
>
> epsilon
>
> zeta
>
> delta
>
> epsilon
>
> zeta
>
> *eta
>
> $
>
>
>
> As you can see the general logic is relatively complex; it is likely that we
>
> can come up with a simpler solution if you describe your actual requirement
>
> in more detail.
hi,
I want to iterate in the inner loop by reading each line till some condition is met.how can i do that. Thanks for this code.
More information about the Python-list
mailing list