【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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值