Python 未处理的stopIteration的os.walk错误

Python 未处理的stopIteration的os.walk错误,python,os.walk,Python,Os.walk,我已经编写了一个python脚本,并希望使用eric ide对其进行调试。当我运行它时,出现了一个错误,说未处理的StopIteration 我的代码片段: datasetname='../subdataset' dirs=sorted(next(os.walk(datasetname))[1]) 我是python新手,所以我真的不知道如何解决这个问题。为什么会出现此错误?如何修复它?将在向下遍历的目录树中生成文件名。它将返回每个目录的内容。由于它是一个异常,当没有更多的目录可迭代时,它将引发

我已经编写了一个python脚本,并希望使用eric ide对其进行调试。当我运行它时,出现了一个错误,说
未处理的StopIteration

我的代码片段:

datasetname='../subdataset'
dirs=sorted(next(os.walk(datasetname))[1])
我是python新手,所以我真的不知道如何解决这个问题。为什么会出现此错误?如何修复它?

将在向下遍历的目录树中生成文件名。它将返回每个目录的内容。由于它是一个异常,当没有更多的目录可迭代时,它将引发
StopIteration
异常。通常,当您在
for
循环中使用它时,您不会看到异常,但这里您直接调用它

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

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

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

try:
    dirs = sorted(next(os.walk('./doesnt-exist')))
except StopIteration:
    pass # Some error handling here
另一个选项是使用
try
/
来捕获异常:

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

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

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

可以但是我怎么能解决这个问题呢?@Sibi在回答中添加了几个例子是的,这个错误已经解决了,但是现在我在下面两行中得到了一个新的错误,在
leng=len(dirs)
“名称'dirs'未定义”
@Sibi如果您使用
进行循环,则可以在循环之前执行
dirs=None
。使用try-except,您可以在except块中执行相同的操作。然后,如果
dirs
None
,那么稍后您就会知道它不存在。如果您同意将不存在的目录和空目录视为相同的目录,则可以将空列表分配给
dirs
,而不是
None
。因为我看不到其余的代码,所以我真的不知道什么是“正确”的方法。