|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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)
会出现permission error的问题,是怎么回事呢?已经使用管理员权限运行IDLE
运行结果如下:
请输入待查找的初始目录:D:\\
请输入需要查找的目标文件:happy.txt
D:\\happy.txt
Traceback (most recent call last):
File "C:\python code\fish\030_2example.py", line 14, in <module>
search_file(start_dir, target)
File "C:\python code\fish\030_2example.py", line 9, in search_file
search_file(each_file, target) # 递归调用
File "C:\python code\fish\030_2example.py", line 3, in search_file
os.chdir(start_dir)
PermissionError: [WinError 5] 拒绝访问。: 'System Volume Information'
本帖最后由 jackz007 于 2019-3-23 00:50 编辑
是特殊目录的访问权限出现了问题,用 try ... except ... finally 加以处理,如果目录不能访问就放弃或直接跳过,除此以外,没有别的更好办法。
楼主可以再测试一下下面的代码:
- import os
- def search_file(start_dir , target) :
- try:
- os . chdir(start_dir) # 风险语句
- try:
- 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) # 递归调用
- except:
- pass
- finally:
- os . chdir(os.pardir) # 递归调用后切记返回上一层目录
- except:
- pass
- start_dir = input('请输入待查找的初始目录:')
- target = input('请输入需要查找的目标文件:')
- search_file(start_dir, target)
复制代码
|
|