0

i was just wondering why my program, even though it finds the data, cannot write tesla's data even though it writes the data of every other stock. Here is my code:

import requests, bs4, logging

stocks = {"google":"694653","amazon":"660463","apple":"22144","hack":"898127760101820","facebook":"296878244325128",
          "biotech":"700203","construction":"705971","nvidia":"662925","netflix":"672501","tesla":"12607212","":""}

new = open("Stocks.txt","w")

for stock in stocks:

    website = requests.get("https://www.google.ca/finance?cid=" + stocks[stock])
    website.raise_for_status()

    html = bs4.BeautifulSoup(website.text,"html.parser")

    price = (html.select(("#ref_%s_l") % stocks[stock])[0]).getText()
    change = (html.select(("#ref_%s_cp") % stocks[stock])[0]).getText()

    today = open("Stocks.txt","a")
    today.write(stock + ": " + price + "  " + change + 2*"\n")
Lmorj
  • 41
  • 1
  • 2
  • 5

1 Answers1

0

A good way of avoiding these kind of file closing issues is to use the with construction:

Replace for instance

new = open("Stocks.txt","w")

with

with open("Stocks.txt","w") as new:
    new.write ("XXX")
    #you can do all kinds of stuff here

This will automatically close the file after you are done with the indented part. You can read up on this here and in this SO question.

patrick
  • 4,455
  • 6
  • 44
  • 61