需求:编写一个程序,用户输入文件名以及开始搜索的路径,搜索该文件是否存在。如果遇到文件夹,则进入文件夹继续搜索。
程序实现如下:
请输入待查找的初始目录:E:\Python Program
请输入需要查找的目标文件:donelli.jpg
E:\Python Program\neural_artistic_style-master\images\donelli.jpg
tips:如果遇到文件夹,则进入文件夹继续搜索。需要使用递归。
# -*- coding: utf-8 -*-
import os
def search_file(start_dir,target_name):
os.chdir(start_dir) #os.chdir() 方法用于改变当前工作目录到指定的路径。
for each_file in os.listdir(os.curdir):
if each_file==target_name:
print (os.getcwd()+os.sep+each_file) #os.sep 根据你所处的平台,自动地采用相应的分割符号。
if os.path.isdir(each_file):
search_file(each_file,target_name) #递归调用
os.chdir(os.pardir) # 切换到上级目录 递归调用后,切记返回上一层目录
start_dir=input("请输入待查找的初始目录:")
target_name=input("请输入需要查找的目标文件:")
search_file(start_dir,target_name)