f.write('string') only writing once in a while true loop in python

Viewed 94

Ok, so I was trying to make a script that would scrape the current price of bitcoin every 3 seconds or so, print that number and then write it into a text file for later use, but when I run the below code, it only writes the variable into the text file the first time I run the code

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)
1 Answers

If you want to write all the prices to the file, line-by-line, write a newline too:

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)

Also, since the file isn't closed, use context manager:

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)
Related