[Tutor] Searching in a file

Alan Gauld alan.gauld at btinternet.com
Thu Jan 14 00:05:11 CET 2010


"Hugo Arts" <hugo.yoshi at gmail.com> wrote

> the most obvious answer would be to take a look at the 'next()'
> function, that should solve this immediate problem.

This would be nmy advice too, but you need to get an explicit iterator to 
use it.

it = open(.....)
for line in it:
    if 'NEW' in line:
        ln = it.next()

etc...

> Yet another approach is to abandon the for loop entirely, and use a
> while loop combined with the readline method,

I prefer the next() approach.

But a third option is to use a split and apply it to the whole file as
a string thereby breaking the file into as many chunks as start with
a line containing 'NEW'...

data = open(....).read()
for chunk in data.split('NEW'):
     for line in chunk.split('\n'):  # create lines out of the chunks - you 
may not need this
          # process lines till done

Just a thought.

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




More information about the Tutor mailing list