我已经编写了一个python脚本,并想使用eric ide对其进行调试。当我运行它时,弹出错误提示unhandled StopIteration
我的代码段:
datasetname='../subdataset'
dirs=sorted(next(os.walk(datasetname))[1])
我是python的新手,所以我真的不知道如何解决这个问题。为什么会弹出此错误,我该如何解决?
os.walk
将在目录树中生成文件名,将其向下滚动。它将返回每个目录的内容。由于它是生成器,因此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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句