pythonos.walk

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


Solution

  • 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