Regex Python Help

Terry Reedy tjreedy at udel.edu
Tue Mar 24 15:53:19 EDT 2015


On 3/24/2015 2:13 PM, gdotoli at gmail.com wrote:
> I am creating a tool to search a filesystem for one simple string.
> I cannot get the syntax correct.
> Thank you in advance for your help.
>
> import sys
> import re
> import os
> path='/'
> viewfiles=os.listdir(path)

listdir is not recursive, so this code will only search files in the one 
directory, not the whole filesystem.  You need to use os.walk and modify 
the code to do the latter.

> for allfiles in viewfiles:
>      file= os.path.join(path, allfiles)
> text=open(file, "r")
> for line in text:
>      if re.match("DECRYPT_I", line):
>          print line,

You appear to have used a mixture of spaces and tabs for indents.  That 
works in 2.x, but not in 3.x.  You open but do not close files, which 
could be a problem if you open and search 100000 files in a filesystem. 
  Use a with statememt.  'allfiles' is a bad name because it get bound 
to a single file.

for file in viewfiles:
     with open(os.path.join(path, file)) as text:
         for line in text:
             if re.match("DECRYPT_I", line):
                 print(line)

-- 
Terry Jan Reedy




More information about the Python-list mailing list