#!/usr/bin/python3 import os def find_file(dir_path, file_name): if os.path.exists(dir_path): file_tree = os.walk(dir_path) # 返回一个生成器,可以获取到文件树 else: print("查找目录地址不存在") return ret_path = [] for path, catlog, files in file_tree: if file_name in files: ret_path.append(path+file_name) print("%s/%s" % (path, file_name)) if ret_path: print(ret_path) else: print("在 %s 目录下没有找到指定文件" % dir_path) if __name__ == "__main__": find_file('/root', 'file_lookup.py')
import os "D:\developer\qiubai.txt" def test(): # 用户传入的路径和文件名 file_path = "D:\developer\qiuai.txt" # file_path = "D:\developer\python_spider\qiubai\qiubai.txt" # 取文件名 file_name = file_path.split("\\")[-1] # 取路径 file_list = file_path.split("\\")[:-1] file_path = "\\".join(file_list) # 判断是否存在文件 for root,dirs,files in os.walk(file_path): if file_name in files: print(root) print("YES") break else: print("NO") if __name__ == '__main__': test()