首页 > 解决方案 > 将我的实时输出打印到 txt 文件不起作用 python

问题描述

我的脚本每秒打印一次比特币价格,但我希望将输出打印到我的 txt 文件,但它只将 1 个价格打印到 txt 文件,但我希望每个输出到我的 txt 文件

我的代码

import bs4
import requests
from bs4 import BeautifulSoup
import datetime

x = datetime.datetime.now()

def parsePrice():
    r = requests.get('http://finance.yahoo.com/quote/BTC-USD?p=BTC-USD',
                     verify=False)
    soup =\
        bs4.BeautifulSoup(r.text)
    price =\
        soup.find_all('div', {'class': 'D(ib) smartphone_Mb(10px) W(70%) W(100%)--mobp smartphone_Mt(6px)'})[0].\
            find('span').text
    return price


while True:
    print('Bitcoin prijs: ' + str(parsePrice()),'  ::  ',x.strftime("%d, %B"))

     with open("koersen.txt", "w") as out_file:
       for i in range(len(parsePrice())):
          out_string = ""
            out_string += str(parsePrice())
          out_string += "," + str(a)
            out_string += "\n"
          out_file.write(out_string)

标签: pythonpython-3.xfileprinting

解决方案


这里

with open("koersen.txt", "w") as out_file:

您正在以写入模式打开文件。所以它会覆盖所有以前的数据。以附加模式打开它:"a""w+"

更新

尝试像这样写入您的文件:


while True:
    print('Bitcoin prijs: ' + str(parsePrice()),'  ::  ',x.strftime("%d, %B"))

    with open("koersen.txt", "w+") as out_file:
        out_string = str(parsePrice()) + "\n"
        out_file.write(out_string)

推荐阅读