2012-03-14 3 views
0

디렉토리 트리에서 파일 목록을 찾으려고합니다. 본질적으로 나는 (~ 500)을 검색하고자하는 모든 용어를 텍스트 파일로 제공하고 디렉토리와 서브 디렉토리에서 그것들을 찾는다. 그러나 나는 코드가 걸리는 단계와 모든 폴더에서 검색하지 않고 조기에 끝나는 단계에 문제가 있습니다. 내가 잘못이야 위치에Py 폴더 및 하위 폴더의 파일 검색

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() 

모든 아이디어 : 내가 사용

코드 (pattern 텍스트 파일의 이름입니다)입니까?

+1

:

그 어떤 다른 문제를 해결하는 대신이 시도 왜냐하면'file'은 내장 모듈의 클래스이기 때문입니다. – hochl

+0

파일 이름을 다른 것으로 변경했습니다. 당신이 언급 한 construt을 조사하겠습니다. – Andres

+0

그래서 문제의 증상은 정확히 무엇입니까? –

답변

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

+0

내 대답이 도움이된다면 (http://meta.stackexchange.com/a/5235/155356) 확인 표시의 개요를 클릭하여 [수락 할 수 있습니다] 답에. –

0

for line in filefile 처음으로 선을 소비하고 그 후 때마다 비어 있습니다. `당신의 파일을`호출하지 않는 : 나는 오픈 (패턴, 'RU')으로 구조를`사용하는 F로 제안

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

+0

죄송합니다. 질문을 잘못 읽고 각 파일에서'grep'과 동일한 명령을 실행하고 싶다고 생각했습니다. 이제 실제로 파일 이름과 일치하는지 확인합니다. 나는 그 모범을 바로 잡았다. –

관련 문제