os.walk error of unhandled stopIteration
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
RaviTej310
Updated on August 31, 2022Comments
-
RaviTej310 over 1 year
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 almost 8 yearsOkay! But how could I fix this?
-
niemmi almost 8 years@Sibi Added couple examples to answer
-
RaviTej310 almost 8 yearsYes, 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"
-
niemmi almost 8 years@Sibi If you're using
for
loop you could dodirs = None
before the loop. With try except you could do the same within except block. Then ifdirs
isNone
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 todirs
instead ofNone
. Since I can't see the rest of the code I can't really tell what's the "correct" approach.