目录树

代码

import os
import argparse


def get_directory_tree(root_dir, show_hidden=False):
    """
    递归获取目录树结构

    参数:
        root_dir: 根目录路径
        show_hidden: 是否显示隐藏目录(以.开头的目录)

    返回:
        目录树结构的嵌套字典
    """
    # 检查目录是否存在
    if not os.path.isdir(root_dir):
        raise ValueError(f"目录不存在: {root_dir}")

    tree = {"name": os.path.basename(root_dir), "children": []}

    try:
        # 获取目录下的所有条目
        entries = os.listdir(root_dir)

        for entry in entries:
            entry_path = os.path.join(root_dir, entry)

            # 跳过文件,只处理目录
            if not os.path.isdir(entry_path):
                continue

            # 如果不显示隐藏目录,且目录以.开头,则跳过
            if not show_hidden and entry.startswith('.'):
                continue

            # 递归处理子目录
            tree["children"].append(get_directory_tree(entry_path, show_hidden))

    except PermissionError:
        # 没有权限访问的目录,标记为[权限不足]
        tree["name"] += " [权限不足]"
    except Exception as e:
        # 其他错误
        tree["name"] += f" [错误: {str(e)}]"

    return tree


def print_tree(tree, indent="", last=True):
    """
    打印目录树结构

    参数:
        tree: 由get_directory_tree返回的目录树字典
        indent: 缩进字符串
        last: 是否为最后一个子节点
    """
    # 确定当前行的前缀
    prefix = "└── " if last else "├── "
    print(indent + prefix + tree["name"])

    # 计算下一级的缩进
    if last:
        new_indent = indent + "    "
    else:
        new_indent = indent + "│   "

    # 递归打印子目录
    children = tree["children"]
    for i, child in enumerate(children):
        print_tree(child, new_indent, i == len(children) - 1)


def main():
    # 解析命令行参数
    parser = argparse.ArgumentParser(description='显示目录的树形结构')
    parser.add_argument('directory', nargs='?', default=fr'H:\2025年10月13日——数据集处理', help='要显示的目录路径(默认当前目录)')
    parser.add_argument('-a', '--all', action='store_true', help='显示隐藏目录')
    args = parser.parse_args()

    try:
        # 获取绝对路径
        root_dir = os.path.abspath(args.directory)
        print(f"目录树结构: {root_dir}")
        print("-" * (len(root_dir) + 5))

        # 生成并打印目录树
        tree = get_directory_tree(root_dir, args.all)
        print_tree(tree)

    except Exception as e:
        print(f"错误: {e}")


if __name__ == "__main__":
    main()
    print(f"finished")

 

posted @ 2025-11-27 12:28  Blairs  阅读(3)  评论(0)    收藏  举报
Live2D