2011-03-21 4 views
0

내 프로그램에서 특정 유형의 모든 파일을 로깅했는지 확인하고 싶습니다. 그래서 본질적으로, 나는 단지 파일 이름을 가진 logfile을 가지고있다. 그리고 나서 파일이 존재 하는지를 검사하기 위해 파일을 실행하는 함수를 사용한다. 이제 그 내용은 거대합니다. 그러나 저는 이것을 원유 방법으로했습니다. 불행히도 제대로 작동하지 않습니다.파일에서 파일 이름 찾기 (디렉토리에서)

import subprocess 
import sys 
import signal 
import shutil 
import os, fnmatch 


#open file to read 
f=open("logs", "r") #files are stored in this directory 
o=open("all_output_logs","w") 
e=open("missing_logs",'w') 


def locate(pattern, root=os.curdir): 
    '''Locate all files matching supplied filename pattern in and below 
    supplied root directory.''' 
     #ignore directories- ignore works, just uncomment. 
    #ignored = ["0201", "0306"] 
    for path, dirs, files in os.walk(os.path.abspath(root)): 
     #for dir in ignored: 
      # if dir in dirs: 
       #dirs.remove(dir) 
     for filename in fnmatch.filter(files, pattern): 
      yield os.path.join(path, filename) 



    #here i log all the files in the output file to search in 
for line in f: 
    if line.startswith("D:"): 
     filename = line 
     #print line 
     o.write(filename) 

f.close() 
o.close() 
r.close() 

i=open("all_output_logs","r") 
#primitive search.. going through each file in the directory to see if its there in the log file 
for filename in locate("*.dll"): 
    for line in i: 
     if filename in i: 
      count=count+1 
      print count 
     else: 
      e.write(filename) 

내 더미 변수 카운트가 인쇄되는 표시되지 않습니다, 나는 단지리스트의 중간에 어떻게 든 하나의 파일 이름을 얻는다.

답변

1

문제는 첫 번째 패스에서만 파일의 행이 읽히고 파일 객체 (i 경우)가 in 연산자 사용을 지원하지 않는다는 것입니다. 코드를 다음과 같이 변경할 수 있습니다.

lines = open("all_output_logs","r").readlines() 
for filename in locate("*.dll"): 
    for line in lines: 
     if filename in line: 
      count=count+1 
      print count 
     else: 
      e.write(filename) 

그러나 여전히 비효율적이며 다소 어색합니다.

f = open("all_output_logs","r") 
for filename in locate("*.dll"): 
    f.seek(0) 
    for line in f: 
     if filename in line: 
      count=count+1 
      print count 
     else: 
      e.write(filename) 
: 로그 파일이 이 그때는 아마 메모리에 모든 것을 읽고 "큰"원하지 않는, 그래서 각 조회에 되감기해야 말 때문에

로그 파일의 각 행에 포함 할 내용을 지정하지 않았으므로 in 연산자를 사용하지 않았습니다. 하나는 filename == line.strip()이 올바른 비교 일 것으로 예상했을 것입니다.