Tag:python
Article From:https://segmentfault.com/q/1010000012141028
Question:

A function is written to find files or folders recursively, but the value is returned to a value.None,The code is as follows:

#!/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  # printIt can output the results normally, but return is None. Why?If entry.is_dir (follow_symlinks=True):If enTry.name = = file:Print (entry.path)Return entry.pathElse:FindFile1 (path=entry.path, file=file)RetuRN findFile1 (path=entry.path, file=file) when return is used here, the output of print is gone. Why?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)

Run function:

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

#When return findFile1 (path=entry.path, file=file) is used in the recursion, the result is directly None, and the print output is gone.$Python D:\scripts\Funny\find_file.py -p D:\sublime_coding -f notes.pyNone

Ask where the question is, thank you.

Answer 0:

elseThere, write it directly

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

————————————————
Your code problem should be on the next level. The return value of the recursive function can not be passed to the upper layer correctly.
Give you a useful code:

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

Leave a Reply

Your email address will not be published. Required fields are marked *