4

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?

RaviTej310
  • 1,635
  • 6
  • 25
  • 51

2 Answers2

6

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
niemmi
  • 17,113
  • 7
  • 35
  • 42
  • Okay! But how could I fix this? – RaviTej310 May 18 '16 at 03:32
  • @Sibi Added couple examples to answer – niemmi May 18 '16 at 03:45
  • Yes, that error has been resolved but now I'm getting a new error two lines below in `leng=len(dirs);` saying `"name 'dirs' is not defined"` – RaviTej310 May 18 '16 at 04:03
  • @Sibi If you're using `for` loop you could do `dirs = None` before the loop. With try except you could do the same within except block. Then if `dirs` is `None` later you know that it didn't exist. If you're ok with considering non-existing and empty directory the same you could assign empty list to `dirs` instead of `None`. Since I can't see the rest of the code I can't really tell what's the "correct" approach. – niemmi May 18 '16 at 05:04
0

In my case, python 3.6, next(os.walk(whatever_directory)) raised a StopIteration exception because whatver_directory was actually a file.

vpap
  • 1,389
  • 2
  • 21
  • 32