题目:编写一个程序,用户输入文件名以及开始搜索的路径,搜索该文件是否存在。如遇到文件夹,则进入文件夹继续搜索。
代码:
path = []
all_files = []
def search(start_path, target_file):
os.chdir(start_path)
for each_file in os.listdir(os.curdir):
if each_file == target_file:
path.append(os.getcwd() + os.sep + each_file)
if os.path.isdir(each_file):
search(each_file,target_file)
os.chdir(os.pardir)
start_path = input("请输入起始路径:")
target_file = input("请输入目标文件:")
search(start_path, target_file)
if len(path) == 0:
print("%s目录下不存在文件%s" %(start_path, target_file))
else:
for each in path:
print(each)