iterating over a file with two pointers

Dave Angel davea at davea.name
Wed Sep 18 07:39:56 EDT 2013


On 18/9/2013 07:21, Chris Angelico wrote:

> On Wed, Sep 18, 2013 at 9:12 PM, nikhil Pandey <nikhilpandey90 at gmail.com> 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.
>
> After the inner loop finishes, do you want to go back to where the
> outer loop left off, or should the outer loop continue from the point
> where the inner loop stopped? In other words, do you want to locate
> overlapping sections, or not? Both are possible, but the solutions
> will look somewhat different.
>

In addition, is this really a text file?  For binary files, you could
use seek(), and manage things yourself.  But that's not strictly legal
in a text file, and may work on one system, not on another.

I'd suggest you open the file twice, and get two file objects.  Then you
can iterate over them independently.

Or if the file is under a few hundred meg, just do a readlines, and do
the two iterators over that.  That way, the inner loop could just
iterate over a simple slice.



infile = open(....  "rb")
lines = infile.readlines()
infile.close()

for index, line in enumerate(lines):
    for inner in lines[index+1:20]:
         ...




-- 
DaveA




More information about the Python-list mailing list