pyhton递归
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)
想问一下如果递归调用后没有返回上一层目录是会导致什么问题呢? 本帖最后由 Stubborn 于 2021-2-22 00:51 编辑
假设搜索A目录,其A目录包含A1,A2两个目录,需要搜索的文件在A2目录中出现。
你可以在判断调用前打印看下,可以很直观的明白为什么要返回上一层的原因。
print(f"path:{os.getcwd()}, each_file:{each_file}")
if os.path.isdir(each_file):
初次调用发现A1,A2两个文件夹,遍历的时候会遍历A1,A2文件夹。
搜索A1文件夹是,工作路径是*A。因为使用os.chdir(start_dir)校准工作路径,搜索完之后,工作路径已经变成了*A\A1
搜索A2文件夹时,工作路径变成了*A\A1。在这个工作路径里面是没有A2文件。导致原本应该搜索A2文件失败。
path:C:\Users\stubbron\Desktop\Gobang\img\A, each_file:A1
path:C:\Users\stubbron\Desktop\Gobang\img\A\A1, each_file:A2
所以应该在调用搜索完毕的时候,返回上一层工作目录。让工作路径重新校准。
如果我想让这个函数返回(return)所有这个target文件的完整路径,怎么改?
试了半天也没有试出来, 能把递归用的好的人真是脑袋好用. 本帖最后由 Stubborn 于 2021-2-22 22:53 编辑
Nate_2020 发表于 2021-2-22 17:03
如果我想让这个函数返回(return)所有这个target文件的完整路径,怎么改?
试了半天也没有试出来, 能把递归用 ...
使用os.path.join(os.getcwd(), path:遍历的文件)
关于遍历文件,可以参考这个:https://fishc.com.cn/thread-131500-1-1.html Stubborn 发表于 2021-2-22 22:51
使用os.path.join(os.getcwd(), path:遍历的文件)
关于遍历文件,可以参考这个:https://fishc.com. ...
路径用 os.getcwd() + os.sep + each_file 也可以,
我现在是想让这个函数返回这么目标文件的路径,
因为可能有多个, 可以用列表的形式返回,
这能实现返回吗?
页:
[1]