find string in file
Tim Chase
python.list at tim.thechases.com
Fri Mar 14 09:57:44 EDT 2008
> I'm neophite about python, my target is to create a programa that
> find a specific string in text file.
> How can do it?
>>> FNAME1 = 'has.txt'
>>> FNAME2 = 'doesnt_have.txt'
>>> TEXT = 'thing to search for'
>>> TEXT in file(FNAME1).read()
True
>>> TEXT in file(FNAME2).read()
False
or that may not be what your teacher wants, but if you give the
homework problem and what you've tried, we might be able to give
you some more quality guidance. :)
The above is *really* *bad* code...horribly suboptimal especially
as files get large. It only returns a boolean value. You might
prefer to enumerate the file's contents and, if any line contains
the search-text, return that line offset without reading the rest
of the file.
-tkc
More information about the Python-list
mailing list