鱼C论坛

 找回密码
 立即注册
查看: 1979|回复: 5

递归函数返回问题

[复制链接]
发表于 2021-2-23 13:46:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
借一鱼油的问题, 想得到结果, 于是需要这个递归函数返回结果, 但不通知怎么弄, 请大神帮忙
我现在是想让这个函数返回这么目标文件的路径,
因为可能有多个, 可以用列表的形式返回,
这能实现返回吗?

递归函数如下


  1. import os

  2. def search_file(start_dir, target) :
  3.     os.chdir(start_dir)
  4.    
  5.     for each_file in os.listdir(os.curdir) :
  6.         if each_file == target :
  7.             print(os.getcwd() + os.sep + each_file) # 使用os.sep是程序更标准
  8.         if os.path.isdir(each_file) :
  9.             search_file(each_file, target) # 递归调用
  10.             os.chdir(os.pardir) # 递归调用后切记返回上一层目录

  11. start_dir = input('请输入待查找的初始目录:')
  12. target = input('请输入需要查找的目标文件:')
  13. search_file(start_dir, target)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-2-23 13:57:55 | 显示全部楼层
你建个全局变量,把结果加进去不就完了么
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2021-2-23 14:04:39 | 显示全部楼层
意思是返回目标文件的完整路径,目标文件可能存在多个?

  1. def search_file(start_dir, target, result=None):
  2.     if result is None:
  3.         result = []
  4.     os.chdir(start_dir)
  5.     for each_file in os.listdir(os.curdir):
  6.         if each_file == target:
  7.             result.append(os.path.join(os.getcwd(), each_file))
  8.         if os.path.isdir(each_file):
  9.             search_file(each_file, target, result)
  10.             os.chdir(os.pardir)
  11.     return result
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2021-2-23 14:17:15 | 显示全部楼层
本帖最后由 jackz007 于 2021-2-23 16:11 编辑
  1. import os

  2. def search_file(start_dir , target) :
  3.     result = []
  4.     try:
  5.         for each_file in os . listdir(start_dir) :
  6.             x = os . path . join(start_dir , each_file)
  7.             if os . path . isfile(x) :
  8.                 if target . lower() == each_file . lower() :
  9.                     result . append(x)
  10.             elif os . path . isdir(x) :
  11.                 result += search_file(x , target)
  12.     except Exception as e:
  13.         print(e)
  14.     return result

  15. start_dir = input('请输入待查找的初始目录:') . strip()
  16. if start_dir :
  17.     target = input('请输入需要查找的目标文件:') . strip()
  18.     if target :
  19.         r = search_file(start_dir , target)
  20.         if r :
  21.             for x in r:
  22.                 print(x)
  23.         else :
  24.             print('抱歉,没有找到目标文件。')
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2021-2-24 16:52:26 | 显示全部楼层
笨鸟学飞 发表于 2021-2-23 13:57
你建个全局变量,把结果加进去不就完了么

it's nice. thanks
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-2-24 16:53:01 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-25 19:10

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表