|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import os
- def find_file(x, y):
- os.chdir(x)
- file = os.listdir('.')
-
- for each in file:
- if each == y:
- print(os.getcwd() + os.sep + each)
- elif os.path.isdir(each):
- find_file(each, y)
- os.chdir(os.pardir)
-
- route = str(input('请输入待查找的初始目录:'))
- name = str(input('请输入需要查找的目标文件:'))
- find_file(route, name)
复制代码
有大佬能教一下吗? 为什么在调用递归函数时更改工作目录只需要输入子目录的名字就可以了?
本帖最后由 Twilight6 于 2020-5-17 23:47 编辑
- import os
- def find_file(x, y):
- os.chdir(x) # 改变工作目录
- file = os.listdir('.') # 列举当前目录的文件名
- for each in file: # 遍历文件名
- if each == y: # 判断是否是您要查找的文件
- print(os.getcwd() + os.sep + each) # 如果是你想找的文件就打印路径
- elif os.path.isdir(each): # 判断当前路径里是否含有文件夹
- find_file(each, y) # 递归查找each文件夹内的文件
- os.chdir(os.pardir) # 返回上级目录
- route = str(input('请输入待查找的初始目录:'))
- name = str(input('请输入需要查找的目标文件:'))
- find_file(route, name)
复制代码为什么在调用递归函数时更改工作目录只需要输入子目录的名字就可以了? - elif os.path.isdir(each): # 因为each这里是代表文件夹了,本身若不输入路径,默认路径是当前工作目录
- find_file(each, y) # 所以你只输入文件夹名会直接在当前工作目录下直接打开文件夹
- # 你这边递归传入的x = each,正好递归时候第一步就执行os.chdir(each)改变了工作目录到each文件夹
复制代码
如果帮助到你了,记得设置最佳~
|
|