python 进程完成匹配的文件列表

1 投票
1 回答
503 浏览
提问于 2025-04-15 23:10

我正在尝试让一段简单的代码正常工作,但不幸的是,我还是个Python初学者。

我的脚本应该返回一个不符合某种模式的文件列表,更多信息可以查看这里: python grep 反向匹配

我的代码在运行,但没有像预期那样处理完整的文件列表:

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 里没有这个字符串

None

如果我把 f = str(os.path.join(path, name)) for print str(os.path.join(path, name)) 改成这样,我就能看到完整的文件列表被打印出来。

我该如何处理整个列表,达到我想要的效果呢?

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

其他部分看起来没问题。

撰写回答