title: grep -r in python
body: <p>i'd like to implement the unix command 'grep -r' in a python function.  i know about commands.getstatusoutput(), but for now i don't want to use that.  i came up with this:</p>
  
  <pre><code>def grep_r (str, dir):
      files = [ o[0]+"/"+f for o in os.walk(dir) for f in o[2] if os.path.isfile(o[0]+"/"+f) ]
      return [ l for f in files for l in open(f) if str in l ]
  </code></pre>
  
  <p>but that of course doesn't use a regex, it just checks if 'str' is a substring of 'l'.  so i tried the following:</p>
  
  <pre><code>def grep_r (pattern, dir):
      r = re.compile(pattern)
      files = [ o[0]+"/"+f for o in os.walk(dir) for f in o[2] if os.path.isfile(o[0]+"/"+f) ]
      return [ l for f in files for l in open(f) if r.match(l) ]
  </code></pre>
  
  <p>but that doesn't work, it doesn't give me any matches even where the former function did.  what changed?  i could just split it up into a bunch of nested loops, but i'm more interested in being succinct than readable.</p>