os.walk error of unhandled stopIteration

二次信任 提交于 2019-12-19 04:40:26

问题


I have written a python script and wanted to debug it using eric ide. When I was running it, an error popped up saying unhandled StopIteration

My code snippet:

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

I am new to python and so, I don't really know how to fix this. Why is this error popping up and how do I fix it?


回答1:


os.walk will generate file names in a directory tree walking it down. It will return the contents for every directory. Since it is a generator it will raise StopIteration exception when there's no more directories to iterate. Typically when you're using it in the for loop you don't see the exception but here you're calling next directly.

If you pass non-existing directory to it will immediately raise the the exception:

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

You could modify your code to use for loop instead of next so that you wouldn't have to worry about the exception:

import os

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

The other option is to use try/except to catch the exception:

import os

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


来源:https://stackoverflow.com/questions/37289653/os-walk-error-of-unhandled-stopiteration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!