|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
如答案中代码所示,不太能偶理解此处的递归调用。我尝试用非递归的方法做,但是没做出来。先将代码贴在下面,求指教。
小甲鱼的代码:
- import os
- def 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)
复制代码
我的代码:
- path_origin = input('请输入待查找的初始目录:')
- file_object = input('请输入需要查找的目标文件')
- while os.path.exists(path_origin) != 1:
- path_origin = input('路径不存在,请输入正确路径')
- while os.path.exists(file_object) !=1:
- file_object = input('文件不存在,请输入正确文件名')
- import os
- list_file = os.listdir(path_origin)
- while file_object not in path_origin:
- for each_file in list_file:
- if os.path.isfile(each_file):
- add = (os.path.split(each_file))[1]
- path_origin = os.path.join(path_origin,add)
- list_file =os.listdir(path_origin)
- elif os.path.ispath(each_file):
- print('原路径下不存在该目标文件')
- break
-
- print(path_origin)
-
复制代码
本帖最后由 jackz007 于 2019-12-30 15:20 编辑
- def search_file(start_dir, target) :
- os . chdir(start_dir) # 这条指令无条件改变了当前路径
- . . . . . .
- search_file(each_file, target) # 递归会把当前路径变更到 each_file,由于 each_file 是当前目录的次级子目录
- os.chdir(os . pardir) # 所以,返回父目录就是恢复当前路径
复制代码
如果把这个代码改成下面这样,递归调用之后,就不再需要返回上级目录了:
- import os
- def search_file(start_dir, target) :
- cwd = os . getcwd() # 改变当前路径之前,先记录原始当前路径
- os . chdir(start_dir) # 改变当前路径
-
- for each_file in os.listdir(os.curdir) :
- if each_file == target :
- print(os . path . join(os . getcwd() , each_file)
- if os.path.isdir(each_file) :
- search_file(each_file , target)
- os . chdir(cwd) # 函数退出前,必须恢复原始当前路径
- start_dir = input('请输入待查找的初始目录:')
- target = input('请输入需要查找的目标文件:')
- search_file(start_dir, target)
复制代码
如果只搜一层目录,那完全可以不用递归,如果要实现遍历所有子目录的效果,这递归恐怕就无法绕开了,当然,你也可以改用 os . walk() 遍历所有子目录,这个方法任何时候都不用递归。
- def search_file(start_dir , target) :
- for root , dirs , files in os . walk(start_dir):
- for file in files:
- if file . lower() == target . lower(): # windows 文件名比较,忽略字母大小写。
- print(os . path . join(root , file))
- start_dir = input('请输入待查找的初始目录:')
- target = input('请输入需要查找的目标文件:')
- search_file(start_dir, target)
复制代码
|
|