reading ftp log file..

Jeff Shannon jeff at ccvcorp.com
Mon Feb 4 16:47:07 EST 2002


Andrew Replogle wrote:

> I'm trying to write a python script that watches an ftp log file.
>
> -----------------------------------
> import os
> import sys
> import smtplib
>
> ServerPath = 'c:\\Program Files\\G6 FTP Server\\'
> logExists = os.path.isfile(ServerPath + 'FTP.log')
> line = "230"
> #print logExists
>
> log = open(ServerPath + 'FTP.log')
> lines = log.read()
> for line in lines:
>  print "someone logged in"
>  break
> -------------------------------------

Your for-loop isn't doing what it seems you think it is.  :)

First, you've set line equal to "230", but you never test whether anything is
equal to line--instead, your for-loop immediately replaces what's in line.

Second, you're reading the entire contents of your file into a single string;
thus, in your for-loop, the name "line" is actually referring to a single
character at a time (as Stefan pointed out).

You might want to do something more like this:

target = "230"
lines = log.readlines()
for line in lines:
    if line.find(target) >= 0:
        print "Target found! %s" % line
        break

Note the use of readlines() to create a list of individual lines, rather than a
single long string.  Then, the for-loop looks at one line at a time (and I've
renamed your other variable to avoid your naming conflict).  I call the find()
method on each line.  This will return the index of the character that target
starts at, or -1 if target is not found.  (If the line starts with the target,
it'll return 0; contrary to many expectations, find() doesn't return a usable
true/false value, so you have to explicitly test equality).  If we *do* find the
target, I print out the entire line, and then exit the for-loop.  Note that by
dropping the break statement, this code will print out *all* the lines in the
file that happen to contain the target--which might be preferable depending on
your requirements.

If you have any other questions, just let us know.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list