Python使用循环将新行写入文本fi

2024-09-24 06:33:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想添加到这个程序中,将每个崩溃点保存到一个文本文件中,并在新行中添加一个新的崩溃点。我从过去的工作中试过这样做,但我似乎无法使它协同工作。在

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

#Required Fields
pageCount = 1287528


#Loop
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()
    except:
        continue
    print(crashPoint[0:-1])
    pageCount+=1

有人能指出我做错了什么,怎么解决它吗?在


Tags: fromimport程序timehtmlsectionfind协同工作
3条回答

如果您只是在append模式下打开输出文件,则执行此操作非常简单:

#Loop
logFile = open("logFile.txt", "a")
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+"\n")
    except:
        continue
    print(crashPoint[0:-1])
    pageCount+=1
logFile.close()

我还没有处理过你所使用的一些模块,所以除非它们做了一些奇怪的事情,否则我无法从中得到启发。我能看到的问题是。。。在

  1. 似乎有一个无限循环,而pageCount>;0和pageCount+=1,所以这可能是个问题
  2. 你要打印到控制台而不是文本文件看起来代码学院有一个很好的关于使用I/O的教程来教你这一点。在

我想如果你修复了无限循环,只需使用文本文件而不是控制台,你就不会有问题了。在

以追加模式打开数据,将数据写入文件。 如果您正在遍历文件循环,只需打开文件一次并继续写入新数据。在

with open("test.txt", "a") as myfile:
    myfile.write(crashPoint[0:-1])

Here是使用python在文件中追加数据的不同方法。在

相关问题 更多 >