2015-05-09 25 views
1

我得到這個錯誤「主循環‘builtin_function_or_method’對象不是可迭代」當我運行下面的代碼:主循環「builtin_function_or_method」對象不是可迭代

我搜索計算器,但不能找到一個答案,我問題...

我檢查了錯別字,但無法找到任何錯誤。請幫幫我!

import urllib2 
import time 
import datetime 

stocksToPull = 'AAPL','GOOG','MSFT','CMG','AMZN','EBAY','TSLA' 

def pullData(stock): 
    try: 
     print 'Currently pulling',stock 
     print str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')) 
     urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=5d/csv' 
     saveFileLine = stock+'.txt' 

     try: 
      readExistingData = open(saveFileLine,'r').read() 
      splitExisting = readExistingData.split('\n') 
      mostRecentLine = splitExisting[-2] 
      lastUnix = mostRecentLine.split(',')[0] 
     except: 
      lastUnix = 0 

     saveFile = open(saveFileLine,'a') 
     sourceCode = urllib2.urlopen(urlToVisit).read() 
     splitSource = sourceCode.split 

     for eachLine in splitSource: 
      splitLine = eachLine.split(',') 
      if len(splitLine) ==6: 
       if splitLine[0] > lastUnix: 
        if 'values' not in eachLine: 
         lineToWrite = eachLine+'\n' 
         saveFile.write(lineToWrite) 

     saveFile.close() 

     print 'Pulled',stock 
     print 'sleeping...' 
     print str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')) 
     time.sleep(300) 

    except Exception,e: 
     print 'main loop',str(e) 

for eachStock in stocksToPull: 
    pullData(eachStock) 
+0

您可能需要添加一個語言標籤才能顯示在適當的社區 - 您將獲得更多關注。 – potatopeelings

回答

4

直接回答

在這裏的代碼:

saveFile = open(saveFileLine,'a') 
sourceCode = urllib2.urlopen(urlToVisit).read() 
splitSource = sourceCode.split 

變化sourceCode.splitsourceCode.split()


如果您想了解更多有關此錯誤,請閱讀下文:

調試時,你最好刪除try ... except塊,尤其是「預期異常」塊,這是非常通用的,你會迷失什麼是錯的。

當刪除try ... except塊,然後再次運行這些代碼,你會得到這樣的錯誤信息:

--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-5-c4fe20f718cd> in <module>() 
    43 
    44 for eachStock in stocksToPull: 
---> 45  pullData(eachStock) 

<ipython-input-5-c4fe20f718cd> in pullData(stock) 
    23  splitSource = sourceCode.split 
    24 
---> 25  for eachLine in splitSource: 
    26   splitLine = eachLine.split(',') 
    27   if len(splitLine) ==6: 

TypeError: 'builtin_function_or_method' object is not iterable 

消息TypeError: 'builtin_function_or_method' object is not iterable與線25,這意味着splitSource相關聯的錯誤是一個builtin_function_or_method並不是iterable

什麼是splitSource?它是sourceCode.split。答案就在這裏。您應該使用()來調用方法,否則您將得到該方法本身。方法str.split顯然不是iterable

+0

謝謝!這使它工作:splitSource = sourceCode.split('\ n') –

+0

很酷。您能否將此答覆標記爲*答案*如果您認爲這有幫助? –