2012-03-14 159 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