递归深度优先查找的返回值的问题

写了个函数实现递归的查找文件或者文件夹,但是返回值一值为None,代码如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import argparse
from collections import deque


def findFile1(path, file):
    '''To implent the simple functions like linux command -- find.'''
    # Depth First Search
    with os.scandir(path) as entryDir:
        for entry in entryDir:
            if entry.is_file(follow_symlinks=True) and entry.name == file:
                print(entry.path)
                return entry.path  # print能正常输出结果,但是return却是None,为什么?
            if entry.is_dir(follow_symlinks=True):
                if entry.name == file:
                    print(entry.path)
                    return entry.path
                else:
                    findFile1(path=entry.path, file=file)
                    # return findFile1(path=entry.path, file=file) 这里用return的时候print的输出都没了,这是为什么

if __name__ == '__main__':
    parser = argparse.ArgumentParser('To implent the simple functions like linux command -- find.')
    parser.add_argument('-p', '--path', type=str, help='the root directory to find file.')
    parser.add_argument('-f', '--file', type=str, help='the file or dir to find.')
    args = vars(parser.parse_args())
    path = args['path']
    file = args['file']

    res = findFile1(path, file)
    print(res)

运行函数:

$ python D:\scripts\funny\find_file.py -p D:\sublime_coding -f notes.py
D:\sublime_coding\matplotlib\notes.py
None

#当递归那一步使用 return findFile1(path=entry.path, file=file) 时,返回结果直接为None了,print输出都没了
$ python D:\scripts\funny\find_file.py -p D:\sublime_coding -f notes.py
None

请教问题出在哪里,谢谢!

阅读 2.8k
1 个回答

else那里,直接写

return findFile1(path=entry.path, file=file)

————————————————
你的代码问题应该是出在下一层递归函数的返回值不能正确地传给上一层
给你贴个有用代码:

def findFile1(path, file):
    with os.scandir(path) as entryDir:
        result = None
        for entry in entryDir:
            if entry.name == file:
                result = entry.path
                break
            elif entry.is_dir(follow_symlinks=True):
                result = findFile1(path=entry.path, file=file)
                if result:
                    break
        return result
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题