python recursion dir返回NONE

时间:2017-06-11 15:34:27

标签: python recursion

1.dirion filesList在dir中,如果找到该文件则返回文件路径

2.print值是真的。但总是返回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

1 个答案:

答案 0 :(得分:1)

我认为你应该只返回函数的末尾,否则python返回None

另外,需要捕获递归返回

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