os.walk 未处理的 stopIteration 错误

os.walk error of unhandled stopIteration

我写了一个 python 脚本,想用 eric ide 调试它。当我在 运行 时,弹出一个错误说 unhandled StopIteration

我的代码片段:

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

我是 python 的新手,所以我真的不知道如何解决这个问题。为什么会弹出此错误,我该如何解决?

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直接

如果您将不存在的目录传递给它,将立即引发异常:

>>> 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