views:

138

answers:

3

Hello, 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.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

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

+1  A: 

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
bobince
A: 

bobince, Thank you for your answer. I'm reaingd up on the 'with' statement. When I try your code:
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 get an error:
logs.py:20: Warning: 'with' will become a reserved keyword in Python 2.6
File "logs.py", line 20
with open('testFile') as f:
^
SyntaxError: invalid syntax
The up arrow is under the N in open. It doesn't seem to like something in line 20. i just don't know what. I've tried used " ", instead of the single quotes. I'll keep reading and trying different things. Any hints would be great.
Thanks
Gary
**I did indent correcty, just doesn't show in the page.

Gary
A: 

bobince,
I got it. I needed to add "from future import with_statement".

Thank you, Gary

Gary