2010-05-26 24 views
1

我想要简单的代码工作,不幸的是我是一个Python初学者。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)) 我可以看到正在打印的整个列表。

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

+0

请正确格式化代码 - 将整个代码块缩进4格,或突出显示它并单击“101010”按钮。 – 2010-05-26 06:51:28

回答

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 

其余的看起来不错。

+0

谢谢一堆Jellybean! – thomytheyon 2010-05-26 06:53:22