tags:

views:

40

answers:

1

I'm trying to get simple code working, unfortunately I'm a python beginner.

My script should return a list of files that doesn't match a pattern, more information here : http://stackoverflow.com/questions/2910106/python-grep-reverse-matching/2910288#2910288

My code is running but doesn't process the complete list of files found as it should :

import sys,os

filefilter = ['.xml','java','.jsp','lass']

path= "/home/patate/code/project"

s = "helloworld"

for path, subdirs, files in os.walk(path):

   for name in files:

      if name[-4:] in filefilter :

         f = str(os.path.join(path, name))

         with open(f) as fp:

             if s in fp.read():

                print "%s has the string" % f

             else:

                print "%s doesn't have the string" % f

This code returns :

/home/patate/code/project/blabla/blabla/build.xml doesn't have the string

None

If I change f = str(os.path.join(path, name)) for print str(os.path.join(path, name)) I can see the whole list being printed.

How can I process the whole list as I wish to ?

A: 

Try using os.path.splitext to check for a matching file extension.

for path, subdirs, files in os.walk(path):
    for name in files:
        if os.path.splitext(name)[1] in filefilter:
            f = str(os.path.join(path, name))
            with open(f) as fp:
                if s in fp.read():
                    print "%s has the string" % f
                else:
                    print "%s doesn't have the string" % f

The rest looks fine.

jellybean
Thanks a bunch Jellybean !
thomytheyon