| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
这段代码会输出9遍 
‘你输入的文件名不存在’ 
求大佬帮忙看看,优化一下,谢谢   
 
- import os
 
  
- def find_file(dir_path, target):
 
 -     Check = 0
 
 -     os.chdir(dir_path)
 
 -     for each_filen in os.listdir(os.curdir):
 
 -         if each_filen in target:
 
 -             print(dir_path + os.sep + each_filen)
 
 -             Check = 1
 
 -         if os.path.isdir(each_filen):
 
 -             find_file(each_filen, target)
 
 -             os.chdir(os.pardir)
 
 -     if Check == 0:
 
 -         print('你输入的文件名不存在!')
 
 -         
 
 - dir_path = input('请输入初始路径:')
 
 - target = input('请输入目标文件(包括后缀名):')
 
 - find_file(dir_path, target)
 
  复制代码 
- if Check == 0:
 
 -         print('你输入的文件名不存在!')
 
  复制代码
递归其实就是调用函数,你这一段代码是一定会执行的,你递归多少次,就执行多少次 
所以说可以放到外面去判断
 - import os
 
 - Check = 0
 
 - def find_file(dir_path, target):
 
 -     
 
 -     os.chdir(dir_path)
 
 -     for each_filen in os.listdir(os.curdir):
 
 -         if each_filen in target:
 
 -             print(dir_path + os.sep + each_filen)
 
 -             Check = 1
 
 -         if os.path.isdir(each_filen):
 
 -             find_file(each_filen, target)
 
 -             os.chdir(os.pardir)
 
 -     
 
 -         
 
 - dir_path = input('请输入初始路径:')
 
 - target = input('请输入目标文件(包括后缀名):')
 
 - find_file(dir_path, target)
 
 - if Check == 0:
 
 -         print('你输入的文件名不存在!')
 
  复制代码 
 
 
 |   
 
 
 
 |