写了个函数实现递归的查找文件或者文件夹,但是返回值一值为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
请教问题出在哪里,谢谢!
else那里,直接写
————————————————
你的代码问题应该是出在下一层递归函数的返回值不能正确地传给上一层
给你贴个有用代码: