python创建pycharm类似的树状目录结构
时间: 2025-03-06 22:40:33 浏览: 34
### 使用Python实现类似PyCharm的树状目录结构
为了创建类似于 PyCharm IDE 中显示的文件和目录树形结构,可以利用 Python 的 `os` 和 `json` 库来遍历指定路径并构建相应的层次结构。下面是一个简单的例子,该方法会递归地访问每一个子目录,并将其内容整理成易于阅读的形式。
#### 构建函数以获取目录结构
```python
import os
from collections import defaultdict
def get_directory_structure(rootdir):
"""
获取给定根目录下的所有文件夹及其内部文件列表,
并返回一个字典表示这种关系。
参数:
rootdir (str): 起始查找位置
返回值:
dict: 文件夹名映射至其内含项名称组成的集合
"""
dir_tree = {}
for base, dirs, files in os.walk(rootdir):
folder_name = os.path.basename(base)
items = set(files + dirs)
# 建立当前层级的关系表
current_level = {folder_name: list(items)}
# 将每一层级的信息加入总的结果集中
parent_dir = os.path.dirname(base).replace(rootdir, '').strip(os.sep)
nested_dict = dir_tree
if parent_dir != '':
path_parts = parent_dir.split(os.sep)
for part in path_parts[:-1]:
nested_dict = nested_dict.setdefault(part, {})
last_part = path_parts[-1] if path_parts else ''
target = nested_dict.setdefault(last_part, {})
# 合并与上一层相同的键
existing_items = target.get(folder_name, [])
updated_items = sorted(set(existing_items + items))
target.update({folder_name: updated_items})
else:
# 如果是在顶层,则直接更新最外层字典
dir_tree.update(current_level)
return dir_tree
```
这段代码定义了一个名为 `get_directory_structure()` 的辅助函数,它接收一个参数——要扫描的目标文件系统的绝对路径字符串 `rootdir`。这个函数通过调用内置模块 `os.walk()` 来迭代整个目录树,收集所有的文件和子文件夹的名字,并按照它们所在的相对路径组织起来形成一个多维嵌套的数据结构[^1]。
#### 打印美观化的输出
为了让最终用户更容易理解所得到的结果,还需要编写另一个功能用来美化输出:
```python
def pretty_print(data, indent=0):
"""打印出漂亮的缩进版文件/文件夹结构"""
for key, value in data.items():
print(' ' * indent + str(key))
if isinstance(value, dict):
pretty_print(value, indent+4)
elif isinstance(value, list):
for item in value:
print(' ' * (indent + 4) + '- ' + str(item))
if __name__ == "__main__":
project_root = './example_project' # 替换成你想查看的具体项目路径
structure = get_directory_structure(project_root)
pretty_print(structure)
```
上述脚本的最后一部分展示了如何使用这两个工具组合在一起工作:先调用 `get_directory_structure()` 函数获得项目的整体布局;再借助于自定义的 `pretty_print()` 方法按需调整格式后呈现出来。这样就可以清晰地看到各个级别的文件分布情况了。
阅读全文
相关推荐




















