Reputation: 43
My script prints every second the bitcoin price but i want the output printed to my txt file but it prints only 1 price to the txt file but i want every output to my txt file
My code
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)
Upvotes: 1
Views: 92
Reputation: 1008
Here
with open("koersen.txt", "w") as out_file:
You are openning file in write mode. So it overwrites all the previous data. Open it in append mode: "a"
or "w+"
Update
Try writing to your file like this:
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)
Upvotes: 2
Reputation: 1277
Instead of opening a file, you can also directly log to STDOUT
console and then use tee
to write to a file direclty.This will allow you view the lines in the terminal directly and also save to file.
For this you just need print statements in and your file.
and your final command will be
python file.py | tee output.txt
Upvotes: 0
Reputation: 1843
First of all welcome to Stackoverflow. You can try changing below code and then let me know if it works for you.
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.writelines(out_string)
instead of write, use writelines.
Upvotes: 0