使用 Python 生成文件夹目录结构

新建一个 python 文件,复制以下代码,运行时指定一下 ignore_list 和 direction_path 即可快速生成文件夹目录结构图。

import re
from pathlib import Path
from pathlib import WindowsPath
from typing import Optional, List


class DirectionTree:
    def __init__(self,
                 direction_name: str = 'WorkingDirection',
                 direction_path: str = '.',
                 ignore_list: Optional[List[str]] = None):
        self.owner: WindowsPath = Path(direction_path)
        self.tree: str = direction_name + '/\n'
        self.ignore_list = ignore_list
        if ignore_list is None:
            self.ignore_list = []
        self.direction_ergodic(path_object=self.owner, n=0)

    def tree_add(self, path_object: WindowsPath, n=0, last=False):
        if n > 0:
            if last:
                self.tree += '│' + ('    │' * (n - 1)) + '    └────' + path_object.name
            else:
                self.tree += '│' + ('    │' * (n - 1)) + '    ├────' + path_object.name
        else:
            if last:
                self.tree += '└' + ('──' * 2) + path_object.name
            else:
                self.tree += '├' + ('──' * 2) + path_object.name
        if path_object.is_file():
            self.tree += '\n'
            return False
        elif path_object.is_dir():
            self.tree += '/\n'
            return True

    def filter_file(self, file):
        for item in self.ignore_list:
            if re.fullmatch(item, file.name):
                return False
        return True

    def direction_ergodic(self, path_object: WindowsPath, n=0):
        dir_file: list = list(path_object.iterdir())
        dir_file.sort(key=lambda x: x.name.lower())
        dir_file = [f for f in filter(self.filter_file, dir_file)]
        for i, item in enumerate(dir_file):
            if i + 1 == len(dir_file):
                if self.tree_add(item, n, last=True):
                    self.direction_ergodic(item, n + 1)
            else:
                if self.tree_add(item, n, last=False):
                    self.direction_ergodic(item, n + 1)


if __name__ == '__main__':
    i_l = [
        '\.git', '__pycache__', 'test.+', 'venv', '.+\.whl', '\.idea', '.+\.jpg', '.+\.png',
        'image', 'css', 'admin', 'tool.py', 'db.sqlite3'
    ]
    tree = DirectionTree(ignore_list=i_l, direction_path='/your_project_path/')
    print(tree.tree)

生成结构图如下:

├────.gitattributes
├────.gitignore
├────app/
│    ├────__init__.py
│    ├────admin.py
│    ├────apps.py
│    ├────migrations/
│    │    ├────0001_initial.py
│    │    └────__init__.py
│    ├────models.py
│    ├────ocr.py
│    ├────serializers.py
│    ├────urls_api.py
│    └────views.py
├────dockerfile_base
├────manage.py
├────media/
├────nginx.conf
├────onlineocr/
│    ├────__init__.py
│    ├────asgi.py
│    ├────settings.py
│    ├────urls.py
│    └────wsgi.py
├────README.md
├────requirements.txt
├────static/
├────templates/
└────uwsgi_params
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 有一些库可以帮助我们可视化文件夹结构。其中一个常用的库是 `os` 模块,它提供了一些用于处理文件和目录的函数。另一个常用的库是 `graphviz`,它可以生成各种图形,包括文件夹结构。 在使用 `os` 模块时,我们可以使用函数 `os.walk` 来遍历文件夹中的所有文件和子文件夹。这个函数返回一个生成器,我们可以使用循环来迭代它,并获取文件夹中的所有项。然后,我们可以使用字符串操作和缩进来打印文件夹结构。以下是一个简单的示例: ```python import os def print_directory_structure(folder_path, indent=''): for root, dirs, files in os.walk(folder_path): print(indent + os.path.basename(root) + '/') for filename in files: print(indent + '├──' + filename) for dirname in dirs: print_directory_structure(dirname, indent + '│ ') # 调用函数并传入文件夹路径 print_directory_structure('path/to/folder') ``` 上面的代码会以树形结构打印文件夹中的所有文件和子文件夹。其中文件夹使用斜杠“/”表示,文件会使用框线与文件名表示。 如果想要更加美观和可交互的文件夹结构可视化,可以使用 `graphviz` 模块。这个模块可以生成各种图形,包括树形结构。下面是一个简单的示例: ```python import os from graphviz import Digraph def draw_directory_structure(folder_path, graph): for root, dirs, files in os.walk(folder_path): graph.node(root) for filename in files: graph.node(filename) graph.edge(root, filename) for dirname in dirs: draw_directory_structure(dirname, graph) graph.edge(root, dirname) # 创建一个空的图形对象 graph = Digraph() # 调用函数并传入文件夹路径和图形对象 draw_directory_structure('path/to/folder', graph) # 展示图形 graph.view() ``` 上面的代码使用 `graphviz` 创建了一个空的图形对象,并通过递归方式遍历文件夹结构,将文件夹和文件作为节点,通过边连接起来。最后,调用 `view` 方法可以在新的窗口中打开图形。这样就可以以更加美观的方式显示文件夹结构

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值