|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
要实现的功能是:搜索指定路径里的文件,看文件是否存在,如果有子文件夹在子文件夹里继续搜索。
下面的代码能符合要求。但如果把第9行注释掉输出的结果一样是为什么?
- def searchfile(f_path,f_name): #搜索文件函数
- os.chdir(f_path)
- for i in os.listdir(os.curdir):
- if i == f_name:
- print(os.getcwd() + '\\' + f_name)
- if os.path.isdir(i):
- searchfile(i,f_name)
- os.chdir(os.pardir)
-
- file_path = input('Please input the start search path: ')
- file_name = input('Please input the file name: ')
- searchfile(file_path,file_name)
复制代码
输出结果:
Please input the start search path: D:\\test
Please input the file name: file.txt
D:\test\file.txt
D:\test\test1\test2\file.txt
D:\test\test1\test2\test3\file.txt
注释掉第9行之后
- def searchfile(f_path,f_name): #搜索文件函数
- os.chdir(f_path)
-
- for i in os.listdir(os.curdir):
- if i == f_name:
- print(os.getcwd() + '\\' + f_name)
- if os.path.isdir(i):
- searchfile(i,f_name)
- os.chdir(os.pardir)
-
- file_path = input('Please input the start search path: ')
- file_name = input('Please input the file name: ')
- searchfile(file_path,file_name)
复制代码
输出结果:
Please input the start search path: D:\\test
Please input the file name: file.txt
D:\test\file.txt
D:\test\test1\test2\file.txt
D:\test\test1\test2\test3\file.txt
二者没有什么差别,那这句话的作用是啥?
因为恰好没有某一个文件夹中的不同文件夹有目标文件,所以输出才一样
它的作用是返回上一级目录
|
|