Python读取文件并获取股票价格
我正在使用一个叫做ystockquote的工具,你可以在这里找到它。简单来说,我有一个文件,里面记录了我所有的股票代码,然后我用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 个回答
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 ...
这一行之后缩进的所有内容都是在打开的文件上进行操作的。当你离开这个代码块后,文件会自动关闭。