答案:使用os模块遍历目录可生成类似tree命令的树形结构,通过递归调用print_tree函数实现缩进显示层级,支持权限错误处理与排序输出。

要生成一个类似命令行 tree 命令的文件树结构,可以利用 Python 的 os.walk() 或递归调用 os.listdir() 遍历目录。下面是一个简洁实用的脚本示例,能清晰输出目录层级结构。
以下脚本会打印指定路径下的文件和文件夹树形结构:
import os
<p>def print_tree(path, prefix="", is_last=True):</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/xiazai/shouce/1725">
<img src="https://img.php.cn/upload/manual/000/000/013/170658211183824.png" alt="doxygen 官方手册">
</a>
<div class="aritcle_card_info">
<a href="/xiazai/shouce/1725">doxygen 官方手册</a>
<p>doxygen是一款好用的程序员辅助工具,它可以让程序添加批添代码更加简单轻松,兼容C++、 C、Java、 Objective-C、Python等主流编程语言,小编提供的doxygen中文手册包含了基本介绍、语法技巧以及进阶技巧等内容,可以让你快速上手操作,有需要的欢迎下载。 基本介绍 Doxygen已经支持生成ANSI编码的chm目录文件(index.hhc)!Doxygen通常是用作生成英文文档的,生成中文文档需要修改输入和输出的码制,这样可以改变解析方式,生成中文文档。但是,你必须意识 到,Dox</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="doxygen 官方手册">
<span>0</span>
</div>
</div>
<a href="/xiazai/shouce/1725" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="doxygen 官方手册">
</a>
</div>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><h1>获取当前路径的名称用于显示</h1><pre class='brush:python;toolbar:false;'>basename = os.path.basename(path)
connector = "└── " if is_last else "├── "
print(prefix + connector + basename)
# 如果是文件,不再深入
if os.path.isfile(path):
return
try:
entries = os.listdir(path)
except PermissionError:
print(prefix + (" " if is_last else "│ ") + "└── [Permission Denied]")
return
entries.sort() # 排序保证输出一致
for i, entry in enumerate(entries):
child_path = os.path.join(path, entry)
is_last_entry = (i == len(entries) - 1)
extension = " " if is_last_entry else "│ "
print_tree(child_path, prefix + (" " if is_last else "│ "), is_last_entry)if name == "main": root_path = "." # 可替换为任意路径,如 "/home/user/project" print_tree(root_path)
运行后输出类似:
.
└── folder1
├── file1.py
└── subfolder
└── test.txt
└── folder2
│ └── data.json
└── main.py
这个脚本轻量、无需依赖第三方库,适合集成到项目工具或自动化脚本中。基本上就这些,不复杂但很实用。
以上就是Python 文件树目录结构生成脚本的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号