efficient text file search.

Ant antroy at gmail.com
Mon Sep 11 09:02:27 EDT 2006


noro wrote:
> Is there a more efficient method to find a string in a text file then:
>
> f=file('somefile')
> for line in f:
>     if 'string' in line:
>          print 'FOUND'
            break
              ^^^
Add a 'break' after the print statement - that way you won't have to
read the entire file unless the string isn't there. That's probably not
the sort of advice you're after though :-)

Can't see why reading the entire file in as the other poster suggested
would help, and seeing as "for line in f:" is now regarded as the
pythonic way of working with lines of text in a file, then I'd assume
that the implementation would be at least as fast as "for line in
f.xreadlines(): "




More information about the Python-list mailing list