2016-05-18 76 views
2

我已經寫了一個python腳本,並希望使用eric ide進行調試。當我運行它,一個錯誤彈出說unhandled StopIterationos.walk未處理的stopIteration錯誤

我的代碼片段:

datasetname='../subdataset' 
dirs=sorted(next(os.walk(datasetname))[1]) 

我是新來的Python等等,我真的不知道如何解決這個問題。爲什麼會出現此錯誤,我該如何解決?

回答

3

os.walk將在目錄樹中生成文件名,並將其放在下面。它會返回每個目錄的內容。由於它是generator,當沒有更多目錄需要迭代時,它將引發StopIteration異常。通常,當您在for循環中使用它時,您看不到例外情況,但在此處直接呼叫next

如果傳遞不存在的目錄,這將立即提升了異常:

>>> next(os.walk('./doesnt-exist')) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
StopIteration 

您可以修改代碼以使用for循環,而不是next,這樣你就不必擔心例外:

import os 

for path, dirs, files in os.walk('./doesnt-exist'): 
    dirs = sorted(dirs) 
    break 

另一種選擇是使用try/except捕獲異常:

import os 

try: 
    dirs = sorted(next(os.walk('./doesnt-exist'))) 
except StopIteration: 
    pass # Some error handling here 
+0

好吧!但我怎麼能解決這個問題? – RaviTej310

+0

@Sibi添加了一些例子來回答 – niemmi

+0

是的,該錯誤已得到解決,但現在我得到了一個新的錯誤在下面兩行'leng = len(dirs);'說''name'dirs'沒有定義「 – RaviTej310