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

Python 文本文件中n行之后的触发器循环,python,file,loops,if-statement,text,Python,File,Loops,If Statement,Text,我想执行一个循环,如果在正在写入的文本文件中只执行了5行。原因是,我希望从文本文件的最后5行计算平均值,如果程序没有5个数字可处理,则抛出一个rumtime错误 #Imports from bs4 import BeautifulSoup from urllib import urlopen import time #Required Fields pageCount = 1290429 #Loop logFile = ope

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

    #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行之后,它会计算平均值,然后显示下一个数字,然后显示新的平均值,依此类推。

您的
循环永远不会结束。我想你是想减少:
pageCount-=1
你的
循环永远不会结束。我想你是想减少:
pageCount-=1

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

#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()

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

#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()

那么,您的代码是否正常工作?如果没有,你能给出一个预期结果和实际结果的例子吗?另外,你有没有想过只检查是否有至少4条线的末端?还是要跳过空行?难道您不能只计算写入的行数,然后继续
,直到计数大于4吗?@spectras编辑以显示更多信息和代码changes@martineau,尝试这样做,使调用该方法变得更容易,但它仍然无法按预期工作,你的代码是否有效?如果没有,你能给出一个预期结果和实际结果的例子吗?另外,你有没有想过只检查是否有至少4条线的末端?还是要跳过空行?难道您不能只计算写入的行数,然后继续
,直到计数大于4吗?@spectras编辑以显示更多信息和代码changes@martineau,尝试过这样做,使调用该方法变得更容易,但它仍然没有达到预期的良好效果,但这并不能解释更新代码中的
ZeroDivisionError
。由于我一直在从网站上提取数据,因此循环将永远持续下去。我现在已经设法让它工作了,但是我还有另一个问题,我现在将把它添加到线程中。这一点很好,但没有解释更新代码中的
ZeroDivisionError
。当我不断从网站中提取数据时,循环将永远持续下去。我现在已经设法让它工作了,但是我还有另一个问题,现在我将把它添加到线程中。