2010-05-28 10 views
0

Python을 배우고 중첩 for 루프를 수행하려고합니다. 내가 마지막으로하고 싶은 것은 파일에 이메일 주소를 넣고이 스크립트가 메일 ID의 전송 IP와 같은 정보를 찾도록하는 것입니다. 지금 난 내 /var/log/auth.log 파일을 테스트하고 있습니다중첩 for 루프

다음

내 코드는 지금까지 있습니다 :

#!/usr/bin/python 

# this section puts emails from file(SpamEmail) in to a array(array) 
in_file = open("testFile", "r") 
array = in_file.readlines() 
in_file.close() 

# this section opens and reads the target file, in this case 'auth.log' 
log = open("/var/log/auth.log", "r") 
auth = log.readlines() 

for email in array: 
    print "Searching for " +email, 
    for line in auth: 
     if line.find(email) > -1: 
       about = line.split() 
       print about[0], 
    print 

내부 'testfile 위'나는 단어를 '분리'내가 아는 원인이 그것은 auth.log 파일에 있습니다. 그냥 '연결 끊기'라는 단어를 찾지 못합니다. "if line.find (email)> -1 :"나는 이메일을 바꿀 수 있고 "disconnect"를 해 스크립트가 잘 찾는다.

아이디어가 있으십니까? 미리 감사드립니다. 게리

+0

출력은 어떻게됩니까? "연결 해제를 찾으십니까?" –

답변

1

난 당신이 요구하는지 아주 잘 모르겠지만, 위의에 명백한 문제는 readlines()\n 줄 끝이있을 것이다 각각의 (잠재적 마지막 제외), 라인의 목록을 반환한다는 것입니다. 따라서 email은 끝에 끝에 개행 문자가 있으므로 끝에 있지 않으면 line에 없습니다.

그래서 아마도 뭔가 같은 :

with open('testFile', 'r') as f: 
    emails= f.read().split('\n') 
with open('/var/log/auth.log', 'r') as f: 
    lines= f.read().split('\n') 

for email in emails: 
    for linei, line in enumerate(lines): 
     if email in line: 
      print 'Line %d, found:' % linei 
      print line 
0

나는 그것을 얻었다. from __future__ import with_statement을 추가해야했습니다.