2012-03-14 158 views
0

我在查找目錄樹中的文件列表。實質上,我提供了一個文本文件,其中包含我要搜索的所有術語(〜500),並讓它在目錄和子目錄中查找它們。但是,我遇到了一些問題 - 我相信 - 代碼在沒有搜索所有文件夾的情況下過早結束的步驟。Py在文件夾和子文件夾中搜索文件

我正在使用的代碼是(pattern是一個文本文件的名稱):

import os 

def locateA(pattern, root): 
    file = open(pattern, 'r') 
    for path, dirs, files in os.walk(root): 
     for word in files: 
      for line in file: 
       if line.strip() in word: 
        print os.path.join(path, word), line.strip() 

上我錯了地方的任何想法?

+1

我建議可以使用結構'與開放(模式,'儒的)爲f:'不要打電話給你的文件'文件「,因爲'file'是內置模塊中的一個類。 – hochl 2012-03-14 17:04:28

+0

將文件的名稱更改爲其他名稱。我會調查你提到的結構。 – Andres 2012-03-14 17:13:23

+0

那麼問題的症狀究竟是什麼? – 2012-03-14 20:47:39

回答

1

除非使用file.seek()重置文件中的當前位置,否則所有或部分問題可能是您只能遍歷文件一次。

確保你尋求迴文件的開頭通過它再次試圖循環前:

import os 

def locateA(pattern, root): 
    file = open(pattern, 'r') 
    for path, dirs, files in os.walk(root): 
     for word in files: 
      file.seek(0)    # this line is new 
      for line in file: 
       if line.strip() in word: 
        print os.path.join(path, word), line.strip() 
+0

啊哈!,好像這是在工作。不知道你只能迭代一次 – Andres 2012-03-14 17:12:43

+0

沒問題,如果我的答案幫助你[接受它](http://meta.stackexchange.com/a/5235/155356),點擊下一步複選標記的大綱到答案。 – 2012-03-14 17:38:51

0

for line in file消耗在file第一次行,然後以後每次都是空的。

試試這個,這解決了一些其他問題:

import os 

def locateA(pattern, root): 
    patterns = open(pattern, 'r').readlines() # patterns is now an array, no need to reread every time. 
    for path, dirs, files in os.walk(root): 
     for filename in files: 
      for pattern in patterns: 
       if pattern.strip() in filename: 
        print os.path.join(path, filename), pattern.strip() 
+0

快速問題,爲什麼我需要'filecontent = open(file,'r').read()'在代碼中?這是否打開目錄中的每個文件? – Andres 2012-03-14 17:10:36

+0

對不起,我誤解了你的問題,並認爲你想在每個文件中執行相同的'grep'。我現在看到你實際上匹配文件名。我糾正了這個例子。 – 2012-03-14 17:14:00