1

我试图让简单的代码工作,不幸的是我是一个 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)) ,我可以看到正在打印的整个列表。

我怎样才能按我的意愿处理整个列表?

4

1 回答 1

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

其余的看起来不错。

于 2010-05-26T06:51:43.667 回答