【python工具盒】快速生成文件夹目录结构

参数为工作路径的名称(仅用于路径输出的开头),需要生成的路径(相对或者绝对都行),跳过的文件/文件夹名称(要求使用list,且按照正则表达式匹配),最终结果保存在类的 tree 中(请参考示例,示例的跳过的文件/文件夹为 pycharm 中常见的文件)

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):
        self.tree += '|' + ('    |' * n) + ('-' * 4) + path_object.name
        if path_object.is_file():
            self.tree += '\n'
            return False
        elif path_object.is_dir():
            self.tree += '/\n'
            return True

    def ignore_judge(self, name: str):
        for item in self.ignore_list:
            if re.fullmatch(item, 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())
        for item in dir_file:
            if self.ignore_judge(item.name):
                if self.tree_add(item, n):
                    self.direction_ergodic(item, n + 1)


if __name__ == '__main__':
    tree = DirectionTree(ignore_list=['\.git', '__pycache__', 'test.+', 'venv', '.+\.whl', '\.idea', '.+\.jpg'])
    print(tree.tree)

猜你喜欢

转载自blog.csdn.net/m0_43448982/article/details/100566597
今日推荐