|

楼主 |
发表于 2018-2-20 20:39:16
|
显示全部楼层
- import os
- def search_file(start_dir, target) :
-
- os.chdir(start_dir)
-
- for each_file in os.listdir(os.curdir) :
- new_path = os.getcwd() + each_file
- if each_file == target :
- print(os.getcwd() + os.sep + each_file)
- if os.path.isdir(each_file) :
- search_file(each_file, target)
- os.chdir('..') # 递归调用后切记返回上一层目录
- start_dir = input('请输入待查找的初始目录:')
- target = input('请输入需要查找的目标文件:')
- search_file(start_dir, target)
复制代码
我在电脑上按照上边的代码运行时是完全正常的。
- import os
- def search_file(start_dir, target) :
-
- os.chdir(start_dir)
-
- for each_file in os.listdir(os.curdir) :
- new_path = os.getcwd() + each_file
- if each_file == target :
- print(os.getcwd() + os.sep + each_file)
- if os.path.isdir(each_file) :
- search_file(each_file, target)
- os.chdir('pardir') # 递归调用后切记返回上一层目录
- start_dir = input('请输入待查找的初始目录:')
- target = input('请输入需要查找的目标文件:')
- search_file(start_dir, target)
复制代码
按照这个代码运行的时候只会查找初始目录下第一个文件夹,之后就不会返回上层目录了 |
|