0

1.recursion filesList in dir,if found the file then return the file path

2.print value is true. but always return NONE

def getFilePath(filepath,fileName):
    files = os.listdir(filepath)
    for fi in files:
        fi_d = os.path.join(filepath, fi)
        if os.path.isdir(fi_d):
            getFilePath(fi_d, fileName)
        else :
            if fi_d.find(fileName) == -1:
                continue
            else:
                print fi_d
                return fi_d
  • Does this answer your question? [Why does my recursive function return None?](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none) – VLAZ Nov 03 '22 at 17:09

1 Answers1

1

I think you should return at the end of the function only, otherwise python returns None

Also, need to capture the recursive return

def getFilePath(filepath,fileName):

    for fi in os.listdir(filepath):
        fi_d = os.path.join(filepath, fi)
        if os.path.isdir(fi_d):
            fi_d = getFilePath(fi_d, fileName)
        else :
            if fi_d.find(fileName) == -1:
                continue
            else:
                print fi_d
    return fi_d
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • To be clearer: your recursive chain's final return can only be None. Only 1 call is going to hit your value return. The stack will then propagate None returns through to the end since the remaining calls will simple reach the end and return the default None. – Alan Leuthard Jun 11 '17 at 16:08
  • use cricket_007 way, the function have return, but return value don't hit my value – seven-zhang Jun 11 '17 at 23:16
  • Not sure what that means, but your function should no longer return None, which at least addresses that part of your question. I don't know what your function's expected output actually is – OneCricketeer Jun 12 '17 at 00:11