python处理匹配的完整列表文件

发布于 2024-09-03 11:22:43 字数 960 浏览 0 评论 0原文

我正在尝试让简单的代码工作,不幸的是我是一个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 没有字符串

如果我将 f = str(os.path.join(path, name)) 更改为 print str(os. path.join(路径, 名称)) 我可以看到整个列表正在打印。

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

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 :
python grep reverse matching

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一腔孤↑勇 2024-09-10 11:22:44

尝试使用 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

其余的看起来都不错。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文