在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ 遞歸深度優(yōu)先查找的返回值的問題

遞歸深度優(yōu)先查找的返回值的問題

寫了個函數(shù)實現(xiàn)遞歸的查找文件或者文件夾,但是返回值一值為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能正常輸出結(jié)果,但是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)

運行函數(shù):

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

#當(dāng)遞歸那一步使用 return findFile1(path=entry.path, file=file) 時,返回結(jié)果直接為None了,print輸出都沒了
$ python D:\scripts\funny\find_file.py -p D:\sublime_coding -f notes.py
None

請教問題出在哪里,謝謝!

回答
編輯回答
尐潴豬

else那里,直接寫

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

————————————————
你的代碼問題應(yīng)該是出在下一層遞歸函數(shù)的返回值不能正確地傳給上一層
給你貼個有用代碼:

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
2017年4月17日 20:36