Skip to content Skip to sidebar Skip to footer

Os.walk Error Of Unhandled Stopiteration

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='../subd

Solution 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

Post a Comment for "Os.walk Error Of Unhandled Stopiteration"