在当前工作目录特定路径下查找并加载指定JSON文件
需求实现方案
需求概述
假设当前工作目录为xyz,需完成以下操作:
- 检查目录中是否存在
src/app路径(可能位于xyz/src/app或xyz/abc/src/app等位置) - 若该路径存在,进一步检查路径下是否有指定JSON文件(如
sample.json) - 若文件存在则加载该文件
原有代码问题
你提供的代码仅从脚本所在目录拼接JSON路径,未实现src/app路径的查找、存在性校验以及JSON文件加载逻辑。
完整实现代码
import os import json def find_and_load_target_json(target_json="sample.json"): # 获取当前工作目录(即假设的xyz目录) current_root = os.getcwd() target_subdir = "src/app" matched_file_paths = [] # 遍历当前目录下所有子目录,查找符合src/app的路径 for root, _, _ in os.walk(current_root): # 验证当前遍历到的目录是否为src/app parent_dir = os.path.basename(os.path.dirname(root)) current_dir = os.path.basename(root) if parent_dir == "src" and current_dir == "app": json_full_path = os.path.join(root, target_json) if os.path.isfile(json_full_path): matched_file_paths.append(json_full_path) # 加载找到的第一个有效JSON文件(可根据需求调整多文件处理逻辑) if matched_file_paths: with open(matched_file_paths[0], "r", encoding="utf-8") as f: data = json.load(f) print(f"已成功加载文件: {matched_file_paths[0]}") return data else: print(f"未找到包含{target_json}的{target_subdir}路径") return None # 调用示例 loaded_json_data = find_and_load_target_json()
代码说明
os.getcwd():获取当前工作目录(即需求中的xyz)os.walk():遍历当前目录下所有层级的子目录,精准匹配src/app路径- 路径匹配逻辑:通过判断当前目录的父目录为
src、当前目录为app来确认目标路径 - 文件加载:找到有效JSON文件后,使用
json.load()读取文件内容;若未找到则返回提示
内容的提问来源于stack exchange,提问作者user14806829
相关产品推荐
相关产品推荐

