第30讲.文件系统 课后作业 02
题目:2. 编写一个程序,用户输入文件名以及开始搜索的路径,搜索该文件是否存在。如遇到文件夹,则进入文件夹继续搜索,程序实现如图:即通过递归查找来根据文件名查找
问题: 个人认为代码并未出现错误
Traceback (most recent call last):
File "D:/qbw1/python/文件练习/homework2.py", line 17, in <module>
search(work_dir+dir_name)
File "D:/qbw1/python/文件练习/homework2.py", line 12, in search
search(each)
File "D:/qbw1/python/文件练习/homework2.py", line 12, in search
search(each)
File "D:/qbw1/python/文件练习/homework2.py", line 7, in search
os.chdir(dir_name)
PermissionError: 拒绝访问。: 'S-1-5-21-344547534-2917072130-1926559820-1001'
用小甲鱼代码依然报错:
错误如下:
Traceback (most recent call last):
File "D:/qbw1/python/文件练习/homework2.py", line 15, in <module>
search_file(start_dir, target)
File "D:/qbw1/python/文件练习/homework2.py", line 10, in search_file
search_file(each_file, target) # 递归调用
File "D:/qbw1/python/文件练习/homework2.py", line 10, in search_file
search_file(each_file, target) # 递归调用
File "D:/qbw1/python/文件练习/homework2.py", line 4, in search_file
os.chdir(start_dir)
PermissionError: 拒绝访问。: 'S-1-5-21-344547534-2917072130-1926559820-1001'
以下是我的代码:
import os
dir_name=input("请输入想查找的目录名: ")
file_name=input("请输入要查找的文件名:")
os.chdir('D:\\'+dir_name)
work_dir=os.getcwd()
def search(dir_name):
os.chdir(dir_name)
work_dir1=os.getcwd()
list=os.listdir(os.curdir)
for each in list:
if os.path.isdir(each):
search(each)
os.chdir(os.pardir)
else:
if os.path.basename(each)==file_name:
print(work_dir1+os.sep+each)
search(work_dir+dir_name)
然后是小甲鱼的代码:
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)
希望有鱼油来帮助一下呜呜呜,万分感谢!
你的work_dir 是一个完整目录,dir_name又是一个目录,他俩相加得到什么??? 如果是想得到下一级目录,也要加上//才可以,
页:
[1]