python进程完成列表文件匹配

时间:2010-05-26 06:38:53

标签: python os.walk

我正在尝试简单的代码工作,不幸的是我是一个python初学者。

我的脚本应返回与模式不匹配的文件列表,更多信息请点击此处: python grep reverse matching

我的代码正在运行但不会处理找到的完整文件列表:

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

此代码返回:

  

/home/patate/code/project/blabla/blabla/build.xml没有字符串

     

如果我改变f = str(os.path.join(path, name)) for print str(os.path.join(path, name)) 我可以看到整个列表正在打印。

如何按我的意愿处理整个列表?

1 个答案:

答案 0 :(得分:0)

尝试使用os.path.splitext检查匹配的文件扩展名。

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

其余的看起来很好。