loop does not count...

John Roth newsgroups at jhrothjr.com
Wed Nov 12 19:22:07 EST 2003


"Jonathan Driller" <jdriller at orchid.org> wrote in message
news:a8cff9fb.0311121513.521ca948 at posting.google.com...
> I am very new to this and would greatly appreciate some insight.
> I am trying to learn Python by doing something useful; write a script
> that will count and output my aggregated visits to my website. I have
> a separate text file that holds the list of uri strings that I want to
> count and then this code. The log is sampleLog.txt.
>
> The problem is that it says all the preceding uris are 0 (they are
> not) and only the last string actually is counted....why is that?
>
> def stats():
>     import sys
>     import string
>     #read the file of current urls - presumes it exists already
>     x = open('urlList.txt')
>     # note this reads as a file, not a list
>     urlFile = x.read()
>     # don't need to close but should
>     x.close()
>     #list what is in text file of urls
>     print "Here is what we check now:\n", urlFile
>     print "\n"
>
>     # len(listName) gives # of list elements
>
>     #turn url listings into list
>     z = open('urlList.txt')
>     urlList = z.readlines()
>     #open log file
>     log = open('sampleLog.txt')
>     logFile = log.read()
>     #initialize counter at 0
>     i = 0
>     # loop through to search for urls
>     while i < len(urlList):
>         # put element into var
>         check = urlList[i]
>         #print out # found and what it was
>         print check, " found" , string.count(logFile, check) ,"times
> \n"
>         # increment for next item - can't do i ++
>         i = i + 1
>     z.close()

The lines you're reading from your test file all end
in a newline, so that may be the reason you're not
finding them in the log file. I suspect that you didn't
end your test file with a return, so that line was
found.

change

    check = urlList[i]

to

    check = urlList[i].strip()

and it might work better.



Also, your imports belong at the module level,
not inside the definition.

John Roth






More information about the Python-list mailing list