开发者

nested for loop

Just learning Python and trying to do a nested for loop. What I'd like to do in the end is place a bunch of email addresses in a file and have this script find the info, like the sending IP of mail ID. For now i'm testing it on my /var/log/auth.log file

Here is my code so far:

#!/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.clo开发者_开发技巧se()

# 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

Inside 'testfile' I have the word 'disconnect' cause I know it's in the auth.log file. It just doesn't find the word 'disconnect'. In the line of "if line.find(email) > -1:" i can replace email and put "disconnect" the scripts finds it fine.

Any idea? Thanks in advance. Gary


I'm not quite sure what you're asking, but an obvious problem with the above is that readlines() returns a list of lines, each of which (except potentially the last) will have a \n line terminator. So email will have a newline at the end of it, so won't be found in line unless it's right at the end.

So perhaps something like:

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


I got it. I needed to add from __future__ import with_statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜