30讲课后题为何递归调用后返回上一层目录???
import osdef search_file(start_dir, target) :
os.chdir(start_dir)
for each_file in os.listdir(os.curdir) :
if each_file == target :
print(os.getcwd() + os.sep + each_file) # 使用os.sep是程序更标准
if os.path.isdir(each_file) :
search_file(each_file, target) # 递归调用
os.chdir(os.pardir) # 递归调用后切记返回上一层目录
start_dir = input('请输入待查找的初始目录:')
target = input('请输入需要查找的目标文件:')
search_file(start_dir, target)
进入下一级路径判断完成后你得出来才行啊 ,只进不出 会无限往下递归的
下面是我写的代码
import os
def fun (path, file_name):
for each in os.listdir(path):
each_path = os.path.join(path, each)
if os.path.isfile(each_path):
if file_name == each:
print(each_path)
else:
fun(each_path, file_name)
path = input('请输入待查找的初始目录:')
file_name = input('请输入需要查找的目标文件:')
fun(path, file_name)
页:
[1]