我正在运行下面的代码,当我对值进行硬编码时运行良好
from nsetools import Nse
nse = Nse()
with open('all_nse_stocks') as nse_stocks:
for stock in nse_stocks:
q = nse.get_quote('INFY')
print q.get('open'), '\t', q.get('lastPrice'), '\t', q.get('dayHigh'), '\t', q.get('dayLow')
看到我已经硬编码了值 nse.get_quote('INFY') 但是当我运行以下代码时,出现以下错误:
from nsetools import Nse
nse = Nse()
with open('all_nse_stocks') as nse_stocks:
for stock in nse_stocks:
q = nse.get_quote(stock)
print q.get('open'), '\t', q.get('lastPrice'), '\t', q.get('dayHigh'), '\t', q.get('dayLow')
错误:
Traceback (most recent call last):
File "test.py", line 6, in <module>
print q.get('open'), '\t', q.get('lastPrice'), '\t', q.get('dayHigh'), '\t', q.get('dayLow')
AttributeError: 'NoneType' object has no attribute 'get'
请帮忙
请您参考如下方法:
NoneType object has no attribute ...意味着你有一个对象是 None ,并且您正在尝试使用该对象的属性。
在你的情况下你正在做 q.get(...) , 所以 q必须是 None .自 q是调用 nse.get_quote(...) 的结果, 该函数必须有可能返回 None .您需要调整代码以应对这种可能性,例如在尝试使用之前检查结果:
q = nse.get_quote(stock)
if q is not None:
print ...
问题的根源可能在于您读取文件的方式。 stock将包含换行符,因此您应该在调用 nse.get_quote 之前将其删除:
q = nse.get_quote(stock.strip())
