pythonpython-3.xos.walk

How to resolve os.walk error in a function?


def getFiles(_root):
    return next(os.walk(_root))[2]

root = "../../../Image/new_m/"
fileList = getFiles(root)  # return file list
fileList = sorted(fileList)

I get this error every time I try to run my function which is supposed to get files from my folder. The error shows StopIteration every time I try to run it.


Solution

  • import os
    def getFiles(_root):
        try:
            return next(os.walk(_root))[2]
        except StopIteration:
            return []  # Return an empty list if the iterator is empty
    
    root = "../../../Image/new_m/"
    fileList = getFiles(root)
    fileList = sorted(fileList)
    

    You can try the above-mentioned code. It will resolve your issue.