python生成树结构

# 生成树结构
def get_trees(data,
              key_column='elementId',
              parent_column='parentId',
              child_column='children'):
    """
    :param data: 数据列表
    :param key_column: 主键字段,默认id
    :param parent_column: 父ID字段名,父ID默认从0开始
    :param child_column: 子列表字典名称
    :return: 树结构
    """
    data_dic = {}
    for d in data:
        data_dic[d.get(key_column)] = d  # 以自己的权限主键为键,以新构建的字典为值,构造新的字典

    data_tree_list = []  # 整个数据大列表
    for d_id, d_dic in data_dic.items():
        pid = d_dic.get(parent_column)  # 取每一个字典中的父id
        if not pid:  # 父id=0,就直接加入数据大列表
            data_tree_list.append(d_dic)
        else:  # 父id>0 就加入父id队对应的那个的节点列表
            try:  # 判断异常代表有子节点,增加子节点列表=[]
                data_dic[pid][child_column].append(d_dic)
            except KeyError:
                data_dic[pid][child_column] = []
                data_dic[pid][child_column].append(d_dic)
    return data_tree_list

def recursion(data, l=None):
    if l is None:
        l = []
    for i in data:
        if 'children' in i:
            children=i.pop('children')
            l.append(i)
            recursion(children,l)
        else:
            l.append(i)
    return l

 

<think>我们参考引用[1]中的思路,使用Python生成项目目录结构文本。核心思路是递归遍历目录,并根据层级关系生成树状结构文本。 ### 解决方案设计 1. **递归遍历目录**:使用`os.walk`或递归函数遍历目标目录 2. **层级表示**:使用缩进和前缀符号表示文件/目录的层级关系 3. **排除处理**:可配置忽略特定目录(如`.git`, `__pycache__`等) 4. **输出格式**:类似引用[1]的树状结构 ### 代码实现 ```python import os from pathlib import Path def generate_directory_tree(root_dir, ignore_dirs=None, max_depth=None, current_depth=0): """ 生成目录树结构文本 :param root_dir: 根目录路径 :param ignore_dirs: 要忽略的目录名列表 :param max_depth: 最大遍历深度(None表示无限制) :param current_depth: 当前深度(内部递归使用) :return: 目录树字符串 """ if ignore_dirs is None: ignore_dirs = ['.git', '__pycache__', '.idea', '.vscode', 'venv', 'env'] # 初始化结果字符串 tree_str = "" # 获取当前目录名称(用于显示) dir_name = os.path.basename(root_dir) if current_depth == 0: tree_str += f"{dir_name}/\n" else: # 根据当前深度计算缩进 indent = "| " * (current_depth - 1) + "|-- " tree_str += f"{indent}{dir_name}/\n" # 检查是否达到最大深度 if max_depth is not None and current_depth >= max_depth: return tree_str try: # 列出当前目录下所有条目并排序(目录在前) entries = sorted(os.listdir(root_dir), key=lambda x: (not os.path.isdir(os.path.join(root_dir, x)), x)) for i, entry in enumerate(entries): full_path = os.path.join(root_dir, entry) # 跳过忽略目录 if os.path.isdir(full_path) and entry in ignore_dirs: continue # 处理子目录 if os.path.isdir(full_path): tree_str += generate_directory_tree( full_path, ignore_dirs, max_depth, current_depth + 1 ) # 处理文件 else: indent = "| " * current_depth # 判断是否是最后一个条目 if i == len(entries) - 1: tree_str += f"{indent}`-- {entry}\n" else: tree_str += f"{indent}|-- {entry}\n" except PermissionError: tree_str += f"{'| ' * current_depth}[Permission Denied]\n" return tree_str def save_tree_to_file(tree_str, output_file): """将目录树保存到文件""" with open(output_file, 'w', encoding='utf-8') as f: f.write(tree_str) if __name__ == "__main__": # 示例用法 root_path = input("请输入要生成目录树的根目录路径(留空则使用当前目录): ") or os.getcwd() output_path = "directory_tree.txt" print(f"正在生成目录树: {root_path}") tree = generate_directory_tree(root_path, max_depth=5) print("\n目录树结构:") print(tree) save_tree_to_file(tree, output_path) print(f"\n已保存到: {output_path}") ``` ### 使用说明 1. **基本使用**:直接运行脚本,输入目标目录(或使用当前目录) 2. **参数调整**: - `ignore_dirs`: 自定义要忽略的目录 - `max_depth`: 限制遍历深度(避免过大目录) 3. **输出示例**: ``` project_root/ |-- .gitignore |-- main.py |-- requirements.txt |-- domain/ | |-- llm/ | | |-- trainer/ | | | |-- __init__.py | | | |-- train_pretrain.py |-- utils/ | |-- logging.py |-- configs/ | |-- pretrain_config.yaml ``` ### 高级功能扩展 1. **图形化界面**:使用`tkinter`添加文件选择对话框 2. **格式美化**:支持输出为Markdown格式(可折叠目录树) 3. **符号链接处理**:显示链接指向的真实路径 4. **文件统计**:添加文件大小、修改时间等元数据 ### 相关问题 1. 如何排除特定文件类型(如`.log`)不显示在目录树中? 2. 如何将目录树转换为Markdown格式以便在文档中使用? 3. 如何统计目录中各类文件的数量和总大小? 4. 如何处理循环符号链接(recursive symlink)避免无限递归? 5. 如何优化超大目录的生成性能? 6. 如何将目录树生成功能集成到现有Python项目中? 通过此脚本,您可以快速生成项目的目录结构文档,便于项目展示和文档编写[^1][^3]。对于更复杂的项目文档生成(如类图、函数文档),建议结合Doxygen等专业工具[^3]。</think># Python项目目录结构生成方案 我将为您介绍几种使用Python生成项目目录结构文本的方法,参考了您提供的引用内容并结合实际应用场景。 ## 方法一:简单递归遍历(参考引用[1]) ```python import os from pathlib import Path def generate_directory_tree(start_path, max_depth=None, prefix=''): """生成目录树结构文本 :param start_path: 起始目录路径 :param max_depth: 最大遍历深度 :param prefix: 前缀字符串(用于递归) :return: 目录树字符串 """ tree_str = "" path = Path(start_path) # 添加当前目录 tree_str += f"{prefix}{path.name}/\n" # 检查是否达到最大深度 if max_depth is not None and max_depth <= 0: return tree_str # 列出所有条目并排序 entries = sorted(os.listdir(path)) entries = [e for e in entries if not e.startswith('.')] # 忽略隐藏文件 for i, entry in enumerate(entries): full_path = path / entry is_last = i == len(entries) - 1 # 确定前缀符号 connector = "└── " if is_last else "├── " new_prefix = prefix + (" " if is_last else "│ ") if full_path.is_dir(): # 递归处理子目录 tree_str += f"{prefix}{connector}" tree_str += generate_directory_tree( full_path, max_depth=max_depth-1 if max_depth else None, prefix=new_prefix ) else: # 添加文件 tree_str += f"{prefix}{connector}{entry}\n" return tree_str # 使用示例 if __name__ == "__main__": project_path = input("请输入项目路径: ").strip() or os.getcwd() max_depth = input("最大深度(留空表示无限制): ") max_depth = int(max_depth) if max_depth.isdigit() else None tree = generate_directory_tree(project_path, max_depth) print("\n项目目录结构:") print(tree) # 保存到文件 with open("project_structure.txt", "w", encoding="utf-8") as f: f.write(tree) print("已保存到 project_structure.txt") ``` ### 输出示例: ``` project_root/ ├── main.py ├── requirements.txt ├── domain/ │ ├── __init__.py │ └── llm/ │ ├── __init__.py │ └── trainer/ │ ├── __init__.py │ └── train_pretrain.py ├── utils/ │ └── logging.py └── configs/ └── pretrain_config.yaml ``` ## 方法二:使用tree库(更专业) ```python from tree import Tree import os def generate_tree_structure(path): """使用tree库生成目录结构""" t = Tree(path) t.depth = float('inf') # 无限深度 t.include_files = True t.exclude_dirs = ['.git', '__pycache__', '.idea'] # 排除目录 return t.render() # 使用示例 if __name__ == "__main__": project_path = input("请输入项目路径: ").strip() or os.getcwd() structure = generate_tree_structure(project_path) print("\n项目目录结构:") print(structure) ``` 安装依赖: `pip install tree` ## 方法三:生成Markdown格式(参考引用[3]) ```python import os def generate_markdown_tree(path, level=0): """生成Markdown格式的目录树""" output = "" indent = " " * level if level == 0: output += f"# {os.path.basename(path)}\n\n" output += "```\n" for item in sorted(os.listdir(path)): if item.startswith('.'): continue # 忽略隐藏文件 full_path = os.path.join(path, item) if os.path.isdir(full_path): output += f"{indent}- **{item}/**\n" output += generate_markdown_tree(full_path, level+1) else: output += f"{indent}- {item}\n" if level == 0: output += "```\n" return output # 使用示例 if __name__ == "__main__": project_path = input("请输入项目路径: ").strip() or os.getcwd() md_tree = generate_markdown_tree(project_path) print("\nMarkdown格式目录结构:") print(md_tree) with open("PROJECT_STRUCTURE.md", "w", encoding="utf-8") as f: f.write(md_tree) ``` ### 输出示例: ```markdown # project_root ``` - **domain/** - **llm/** - **trainer/** - train_pretrain.py - main.py - requirements.txt - **utils/** - logging.py - **configs/** - pretrain_config.yaml ``` ``` ## 方法四:集成到现有项目(参考引用[3]) 您可以在项目中添加一个`generate_docs.py`脚本: ```python # generate_docs.py import os import sys from pathlib import Path def main(): project_root = Path(__file__).parent.parent output_file = project_root / "docs" / "PROJECT_STRUCTURE.md" # 确保docs目录存在 output_file.parent.mkdir(exist_ok=True) # 生成目录结构 structure = generate_directory_tree(project_root, max_depth=4) # 添加标题和说明 markdown_content = f"# 项目目录结构\n\n```\n{structure}\n```\n" # 写入文件 with open(output_file, "w", encoding="utf-8") as f: f.write(markdown_content) print(f"已生成项目结构文档: {output_file}") if __name__ == "__main__": main() ``` ## 高级功能扩展 ### 1. 添加文件统计信息 ```python def add_file_stats(path): """添加文件大小和修改时间""" stat = os.stat(path) size = stat.st_size / 1024 # KB mtime = datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d") return f" ({size:.1f}KB, {mtime})" ``` ### 2. 生成交互式HTML目录树 ```python def generate_html_tree(path): """生成HTML格式的交互式目录树""" # 使用d3.js或类似的库生成交互式树状图 # 可参考Doxygen的HTML输出[^3] pass ``` ### 3. 集成Git信息 ```python import git def add_git_info(path): """添加Git版本信息""" try: repo = git.Repo(path) branch = repo.active_branch.name commit = repo.head.commit.hexsha[:7] return f" [git: {branch}@{commit}]" except: return "" ``` ## 使用建议 1. **简单需求**:使用方法一的自定义函数 2. **专业输出**:使用方法二的`tree`库 3. **项目文档**:使用方法三的Markdown格式 4. **持续集成**:将生成脚本加入CI/CD流程 ## 相关问题 1. 如何排除特定目录或文件不显示在目录树中? 2. 如何将目录树生成功能集成到现有Python项目中? 3. 如何为目录树添加文件大小和修改时间等元数据? 4. 如何生成交互式的HTML目录树? 5. 目录树生成性能如何优化? 6. 如何将目录树与Doxygen等文档工具集成? 这些方法可以帮助您快速生成项目的目录结构文档,便于项目管理和文档编写[^1][^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值