def get_project_tree(start_path: str, original_path: str, tree_data:list):
child_files = os.listdir(start_path)
for child_file in child_files:
if child_file in ['.gitignore', '.idea', 'venv', '__pycache__']:
continue
filepath = os.path.join(start_path, child_file)
# 如果是目录则继续递归处理
if os.path.isdir(filepath):
dir_child = {
"label": child_file,
"children": []
}
if start_path != original_path:
# 如果不等于,则说明当前已经处于其他的子层下,根据子层层级寻找child,并将数据存入
calcu_now = start_path.split("\\")[len(original_path.split("\\")):]
update_dict_value_by_path(tree_data, calcu_now, dir_child)
else:
tree_data.append(dir_child)
get_project_tree(filepath, original_path, tree_data)
# 解决根目录下可能存在文件
elif start_path == original_path:
if not child_file.endswith(".py"):
continue
final_child = {
"label": child_file
}
tree_data.append(final_child)
# 解决子目录下的文件写入对应子目录下
elif start_path != original_path:
if not child_file.endswith(".py"):
continue
# 如果不等于,则说明当前已经处于其他的子层下,根据子层层级寻找child,并将数据存入
calcu_now = start_path.split("\\")[len(original_path.split("\\")):]
final_child = {
"label": child_file
}
update_dict_value_by_path(tree_data, calcu_now, final_child)
else:
raise AttributeError("存在未处理的情况")
# return tree_data
def update_dict_value_by_path(tree_data, path, final_child, tree_tier=0):
if isinstance(path, str):
keys = path.split('.')
elif isinstance(path, list):
keys = path
else:
raise ValueError("不支持的路径类型")
d = tree_data
for child in d:
try:
if child["label"] != path[tree_tier]:
# 不是要找的目录,则继续循环
continue
except IndexError:
# 说明是找到了最后一层,当不做处理,继续执行
continue
# 已经找到了对应的目录,看是不是目标层级
if len(path) == tree_tier + 1:
child["children"].append(final_child)
# 说明时找到了对应的层级目录,但是没到目标层级
tree_tier += 1
update_dict_value_by_path(child["children"], path, final_child, tree_tier)
return tree_data
# 使用示例
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
tree_data = []
get_project_tree(base_dir, base_dir, tree_data)
print(tree_data)
执行结果: