马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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)
'''
=========== RESTART: C:/Users/Administrator/Documents/exercise3002.py ========== #试了两次 都出错,不知识什么原因
请输入待查找的初始目录:C:\\Users
请输入需要查找的目标文件:record.txt
Traceback (most recent call last):
File "C:/Users/Administrator/Documents/exercise3002.py", line 15, in <module>
search_file(start_dir, target)
File "C:/Users/Administrator/Documents/exercise3002.py", line 10, in search_file
search_file(each_file, target) # 递归调用
File "C:/Users/Administrator/Documents/exercise3002.py", line 10, in search_file
search_file(each_file, target) # 递归调用
File "C:/Users/Administrator/Documents/exercise3002.py", line 10, in search_file
search_file(each_file, target) # 递归调用
[Previous line repeated 1 more time]
File "C:/Users/Administrator/Documents/exercise3002.py", line 6, in search_file
for each_file in os.listdir(os.curdir) :
PermissionError: [WinError 5] 拒绝访问。: '.'
>>>
=========== RESTART: C:/Users/Administrator/Documents/exercise3002.py ==========
请输入待查找的初始目录:
=========== RESTART: C:/Users/Administrator/Documents/exercise3002.py ==========
请输入待查找的初始目录:c:
请输入需要查找的目标文件:record.txt
Traceback (most recent call last):
File "C:/Users/Administrator/Documents/exercise3002.py", line 15, in <module>
search_file(start_dir, target)
File "C:/Users/Administrator/Documents/exercise3002.py", line 10, in search_file
search_file(each_file, target) # 递归调用
File "C:/Users/Administrator/Documents/exercise3002.py", line 6, in search_file
for each_file in os.listdir(os.curdir) :
PermissionError: [WinError 5] 拒绝访问。: '.'
>>>
'''
|