finding a regular expression in a file

Kushal Kumaran kushal.kumaran at gmail.com
Tue Apr 24 09:07:57 EDT 2012


On Apr 24, 2012 6:32 PM, "S.B" <hyperboogie at gmail.com> wrote:
>
> Hello friends.
>
> Newb question here.
> I'm trying to find an efficient way to "grep" a file with python.
> The problem is that all the solutions I find on the web read a line at a
time from the file with a "for line in" loop and check each line for the RE
instead of sweeping through the entire file.
> This looks terribly inefficient...
>
> I can read the entire file like so:
> open("/etc/passwd").read()
> and use that in an re.search - e.g:
> re.search("root",open("/etc/passwd").read())
> The above will work BUT it will not interpolate the "\n" as a newline and
will just print the entire file as a long line.
> So if I try to look for '^root' (line starting with root) instead of
'root' it will NOT work
>
> any ideas on how to get around this?
>

You want the re.MULTILINE flag.

http://docs.python.org/py3k/library/re.html#re.MULTILINE

-- 
Regards,
Kushal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120424/69024ebc/attachment.html>


More information about the Python-list mailing list