2010-05-26 25 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