The parameters are the name of the working path (only used at the beginning of the path output), the path that needs to be generated (relative or absolute), the name of the file/folder to be skipped (list is required and matched according to regular expressions), and finally The result is saved in the tree of the class (please refer to the example, the skipped files/folders in the example are common files in 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)