You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过命令行或Python函数打印Django项目目录结构?

如何打印Django项目的目录结构

嘿,我刚入门Django的时候也纠结过这个!教程里那种清晰规整的目录结构看着特别舒服,但自己不知道怎么生成对吧?别担心,用命令行或者写个简单的Python脚本都能轻松搞定,我给你两种实用方案:

一、用命令行快速生成

不同操作系统的命令略有差异,挑适合你的来:

Linux/macOS

大部分类Unix系统可以用tree命令快速生成树形结构,如果你的系统没预装,先安装:

  • Ubuntu/Debian:sudo apt install tree
  • macOS(需要先装Homebrew):brew install tree

安装完成后,进入你的Django项目根目录,运行:

tree -I 'venv'

-I 'venv'是用来过滤掉虚拟环境目录的(毕竟里面全是依赖包,没必要展示)。如果想把结构保存到文件里留作参考,就用:

tree -I 'venv' > project_structure.txt

Windows

Windows默认没有tree命令,但有两种替代方式:

  1. PowerShell原生脚本:
    进入项目根目录,把这段代码复制到PowerShell里运行,就能生成树形结构:

    function Show-Tree {
        param([string]$Path = ".", [string]$Prefix = "")
        $items = Get-ChildItem -Path $Path
        for ($i = 0; $i -lt $items.Count; $i++) {
            $item = $items[$i]
            $isLast = ($i -eq $items.Count - 1)
            Write-Host "$Prefix$(if ($isLast) { '└── ' } else { '├── ' })$($item.Name)"
            if ($item.PSIsContainer) {
                $newPrefix = $Prefix + $(if ($isLast) { '    ' } else { '│   ' })
                Show-Tree -Path $item.FullName -Prefix $newPrefix
            }
        }
    }
    Show-Tree
    
  2. 安装tree命令:
    用Chocolatey包管理器安装:choco install tree,之后在命令提示符里运行:

    tree /F /A
    

    /F会显示所有文件,/A用ASCII字符代替图形符号,避免乱码。

二、用Python函数自定义生成

要是你想自己控制展示逻辑(比如排除特定目录、调整排序方式),写个小Python脚本就很灵活,用Python自带的pathlib模块实现:

from pathlib import Path

def print_django_structure(root_dir, exclude_dirs=None, prefix=""):
    if exclude_dirs is None:
        exclude_dirs = ["venv", "__pycache__"]  # 默认排除的目录
    root = Path(root_dir)
    
    # 筛选并排序条目:目录在前,文件在后,按名称排序
    entries = sorted(
        [e for e in root.iterdir() if e.name not in exclude_dirs],
        key=lambda x: (not x.is_dir(), x.name)
    )
    
    for idx, entry in enumerate(entries):
        is_last = idx == len(entries) - 1
        # 打印当前条目
        print(f"{prefix}{'└── ' if is_last else '├── '}{entry.name}")
        # 递归处理子目录
        if entry.is_dir():
            new_prefix = prefix + ("    " if is_last else "│   ")
            print_django_structure(entry, exclude_dirs, new_prefix)

# 调用函数,传入项目根目录路径(当前目录就用".")
print_django_structure(".")

把这段代码保存成print_structure.py,放在项目根目录运行python print_structure.py,就能得到和教程里一模一样的树形结构啦!要是想排除其他目录,直接修改exclude_dirs参数就行。

内容的提问来源于stack exchange,提问作者DanGoodrick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:31:33