python - f.write('string') 在 python 中只写一次 while true 循环
问题描述
好的,所以我试图制作一个脚本,每 3 秒左右抓取一次比特币的当前价格,打印该数字,然后将其写入文本文件以供以后使用,但是当我运行下面的代码时,它只写我第一次运行代码时将变量放入文本文件
from bs4 import BeautifulSoup
import requests
import time
source = requests.get('https://cryptowat.ch/').text
soup = BeautifulSoup(source, 'lxml')
f= open("bitcoinPrice.txt","w+")
while True:
source = requests.get('https://cryptowat.ch/').text
soup = BeautifulSoup(source, 'lxml')
article = soup.find('span', class_='price').prettify()
split = article.split()
cost = split[2]
price = cost + ' USD'
f.write(price)
print(price)
time.sleep(1)
解决方案
如果你想将所有价格逐行写入文件,也可以写一个换行符:
while True:
source = requests.get('https://cryptowat.ch/').text
soup = BeautifulSoup(source, 'lxml')
article = soup.find('span', class_='price').prettify()
split = article.split()
cost = split[2]
price = cost + ' USD'
f.write(price)
f.write('\n')
print(price)
time.sleep(1)
此外,由于文件未关闭,请使用上下文管理器:
with open("bitcoinPrice.txt","w+") as f:
while True:
source = requests.get('https://cryptowat.ch/').text
soup = BeautifulSoup(source, 'lxml')
article = soup.find('span', class_='price').prettify()
split = article.split()
cost = split[2]
price = cost + ' USD'
f.write(price)
print(price)
time.sleep(1)
推荐阅读
- reactjs - 当我更新子组件的状态变量时,为什么会导致无限循环?
- python - 在python上追加(0)
- youtube - 使用 YouTube Live Stream API 操作流指标
- java - 通过 GTK 的 jar 在 Java 中创建 gnome GUI:CLASSPATH 问题
- node.js - UnhandledPromiseRejectionWarning:错误:请求已被处理
- c++ - UE4 - 使用时旋转错误,但导入时旋转正确
- arrays - 如何正确填充 NxN 矩阵
- oracle - M1芯片支持oracle sqlplus数据库吗?
- flutter - Flutter 在 iOS 开发中是否支持 po 之类的调试命令?
- node.js - 如何将 AWS ACM Private 与 Docker Node.js + nginx 代理一起使用?