python - 将我的实时输出打印到 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)
解决方案
这里
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)
推荐阅读
- flutter - 子小部件中的 setState()
- javascript - 在 Eclipse 中将 jquery 添加到我的“动态 Web 项目”中
- itext - Itext 7 - 梳状字段 - 填写表格
- javascript - 为什么组件内部的函数在 componentDidMount 之前执行?
- apache - cURL vs ab performance testing
- msbuild - 如何解压缩 zip 文件并从中导入 smth 作为构建的一部分?
- flutter - what is the sink in streamcontroller in flutter
- amazon-web-services - 有没有办法按需重新运行 AWS Security Hub CIS 基准?
- git - 更改为 .gitattributes 后 Git 重新签出文件
- reactjs - 如何对使用 Enzyme 在 useEffect 中获取数据的反应钩子组件进行单元测试?