jeudi 21 juillet 2016

Trigger loop after n lines in a text file

I want to execute a loop if and only 5 lines have been executed inside the text file that's being written to. The reason being, I want the average to be calculated from the final 5 lines of the text file and if the program doesn't have 5 numbers to work with, then a rumtime error is thrown.

#Imports
from bs4 import BeautifulSoup
from urllib import urlopen
import time

#Required Fields
pageCount = 1290429


#Loop
logFile = open("PastWinners.txt", "r+")
logFile.truncate()
while(pageCount>0): 
    time.sleep(1)
    html = urlopen('http://ift.tt/29PDsMK' % (pageCount)).read()
    soup = BeautifulSoup(html, "html.parser")

    try:
        section = soup.find('div', {"class":"row panel radius"})
        crashPoint = section.find("b", text="Crashed At: ").next_sibling.strip()
        logFile.write(crashPoint[0:-1]+"\n")
    except:
        continue

    for i, line in enumerate(logFile):             #After 5 lines, execute this
        if i > 4:
            data = [float(line.rstrip()) for line in logFile]
            print("Average: " + "{0:0.2f}".format(sum(data[-5:])/len(data[-5:])))
        else:
            continue

    print(crashPoint[0:-1])
    pageCount+=1
logFile.close()

If anyone knows the solution, or knows a better way to go about doing this, it would be helpful, thanks :).

Aucun commentaire:

Enregistrer un commentaire