finding a regular expression in a file

Jussi Piitulainen jpiitula at ling.helsinki.fi
Tue Apr 24 09:01:56 EDT 2012


"S.B" writes:

> 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?

Check MULTILINE mode in the documentation: ^ "Matches the start of the
string, and in MULTILINE mode also matches immediately after each
newline."



More information about the Python-list mailing list