【问题标题】:Python to read file and give stock pricePython读取文件并给出股价
【发布时间】:2014-04-15 17:57:44
【问题描述】:

我正在使用 ystockquote,它可以在 here 找到。基本上,我有一个包含我所有股票代码的文件,然后我使用 python 来写它并显示每只股票的价格。到目前为止,这是我的代码:

import ystockquote 

def intro():
    # Here you enter the name of your file
    watchlist = raw_input(">")
    open_watchlist = open(watchlist)

   print "What next"
   next = raw_input(">")

   if next == "view":
        for line in open_watchlist:
             quote = ystockquote.get_price(line)
             print "%s: %s" % (line, quote)

intro()

这给出了以下错误:

File "hi.py", line 16, in <module>
    intro()
  File "hi.py", line 13, in intro
    quote = ystockquote.get_price(line)
  File "/Users/Nawaz/plancials_beta/env/lib/python2.7/site-packages/ystockquote.py", line 67, in get_price
    return _request(symbol, 'l1')
  File "/Users/Nawaz/plancials_beta/env/lib/python2.7/site-packages/ystockquote.py", line 31, in _request
    resp = urlopen(req)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 402, in open
    req = meth(req)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1113, in do_request_
    raise URLError('no host given')
urllib2.URLError: <urlopen error no host given>

关于如何让它显示符号和价格的任何想法?谢谢。

【问题讨论】:

  • print "%s: %s" % (line, quuote) 你拼错了'quote'
  • 谢谢我更正了它,但我仍然无法让它工作。我得到this error
  • 看起来像 ystockquote 中的一个错误;如果您只是导入它并在解释器中执行 get_price 是否有效?
  • 是的,它完美无缺。我猜想在尝试使用文件中的名称来获取价格时发生错误。

标签: python file-io stock


【解决方案1】:

您似乎只是在倒数第二行拼错了quote。 :)

但值得一提的是:任何时候打开文件之类的资源时,都应该确保在完成后将其关闭。确保使用 with open 语法完成此操作的最佳方法,如下所示:

def intro():
    watchlist = raw_input(">")
    with open(watchlist) as wl:
        print "What next"
        next = raw_input(">")

        if next == "view":
            for line in wl:
                quote = ystockquote.get_price(line)
                print "%s: %s" % (line, quote)

intro()

缩进比with open ... 行更远的任何内容都是在当前打开的文件中完成的。离开那段代码后,文件会自动关闭。

【讨论】:

  • 谢谢,我一定是打错了。但是,当我纠正它时,我得到this error
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-07
  • 2017-11-26
相关资源
最近更新 更多