在文本文件中的n行之后触发循环

时间:2016-07-21 13:16:27

标签: python file loops if-statement text

我想执行一个循环,如果在写入的文本文件中只执行了5行。原因是,我希望从文本文件的最后5行计算平均值,如果程序没有5个数字可以使用,则抛出朗姆酒错误。

    #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('https://www.csgocrash.com/game/1/%s' % (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 :).

修改

更新代码:

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

#Required Fields
pageCount = 1290429
lineCount = 0

def FindAverage():
    with open('PastWinners.txt') as logFile:
        data = [float(line.rstrip()) for line in logFile]
        print("Average: " + "{0:0.2f}".format(sum(data[-5:])/len(data[-5:])))

#Loop
logFile = open("PastWinners.txt", "r+")
logFile.truncate()
while(pageCount>0): 
    time.sleep(1)
    html = urlopen('https://www.csgocrash.com/game/1/%s' % (pageCount)).read()
    soup = BeautifulSoup(html, "html.parser")

    if lineCount > 4:
        logFile.close()
        FindAverage()
    else:
        continue

    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

    print(crashPoint[0:-1])
    pageCount+=1
    lineCount+=1


logFile.close()

新问题: 程序按预期运行,但是一旦计算并显示平均值,程序就不会再次循环,它会停止。我希望它工作,所以在5行后计算平均值,然后显示下一个数字,然后显示新的平均值等等。

2 个答案:

答案 0 :(得分:0)

你的while循环永远不会结束。我认为你打算减少:pageCount-=1

答案 1 :(得分:0)

最后的问题是循环没有重新启动,只是完成了第一次平均计算。这是因为logFile被关闭而没有重新打开,因此程序认为它并附加到文件,它的工作方式与预期一致。感谢大家的帮助。

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

#Required Fields
pageCount = 1290429
lineCount = 0

def FindAverage():
    with open('PastWinners.txt') as logFile:
        data = [float(line.rstrip()) for line in logFile]
        print("Average: " + "{0:0.2f}".format(sum(data[-5:])/len(data[-5:])))

#Loop
logFile = open("PastWinners.txt", "r+")
logFile.truncate()
while(pageCount>0):
    time.sleep(1)
    html = urlopen('https://www.csgocrash.com/game/1/%s' % (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

    print(crashPoint[0:-1])
    pageCount+=1
    lineCount+=1

    if lineCount > 4:
        logFile.close()
        FindAverage()
        logFile = open("PastWinners.txt", "a+")
    else:
        continue
logFile.close()