Python读取文件并给出股票价格

时间:2014-04-15 17:57:45

标签: python file-io stock

我正在使用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>

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

1 个答案:

答案 0 :(得分: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 ...行缩进的任何内容。在您离开该部分代码后,该文件将自动关闭。