fastest way to test file for string?

pruebauno at latinmail.com pruebauno at latinmail.com
Fri Jun 5 15:54:15 CEST 2009


On Jun 5, 7:50 am, kj <no.em... at please.post> wrote:
> Hi.  I need to implement, within a Python script, the same
> functionality as that of Unix's
>
>    grep -rl some_string some_directory
>
> I.e. find all the files under some_directory that contain the string
> "some_string".
>
> I imagine that I can always resort to the shell for this, but is
> there an efficient way of doing it within Python?
>
> (BTW, portability is not high on my list here; this will run on a
> Unix system, and non-portable Unix-specific solutions are fine with
> me.)
>
> TIA!
> --

You can write your own version of grep in python using os.walk, open,
read and find. I don't know why one would want to do that unless for
portability reasons. It will be pretty hard to beat grep in efficiency
and succinctness. The most sensible thing IMHO is a shell script or
call grep using os.system (or using subprocess).



More information about the Python-list mailing list