Grep Equivalent for Python

sjdevnull at sjdevnull at
Wed Mar 14 21:06:09 CET 2007

On Mar 14, 10:57 am, Marc 'BlackJack' Rintsch <bj_... at> wrote:
> In <et8u0e$k2... at>, Laurent Pointal wrote:
> > Steve Holden a écrit :
> >> Regular expressions aren't really needed here. Untested code follows:
> >> for line in open('/proc/meminfo').readlines:
> > for line in open('/proc/meminfo').readlines():
> for line in open('/proc/meminfo'):

Yeah, that's nicer.

> Of course it's cleaner to assign the file object to a name and close the
> file explicitly after the loop.

For certain definitions of "cleaner" (insert old argument about how
ref-counting semantics or at least immediate gc of locally scoped
variables when leaving scope _should be_ (not _are_) language-
guaranteed because it makes for cleaner, more programmer-friendly code
and often avoids ugly hacks like assigning a spurious name and/or
using "with" constructs).

But if you're going to do that, "with" is the better option IMO:

from __future__ import with_statement
with open('/proc/meminfo') as infile:
  for line in infile:

Of course, that alternative requires Python 2.5

More information about the Python-list mailing list