Given a directory Path object print a visual tree structure
(dir_path: Path, level: int=-1, limit_to_directories: bool=False,
length_limit: int=1000)
| 82 | return ''.join(reversed(parts)) |
| 83 | |
| 84 | def visualize_tree(dir_path: Path, level: int=-1, limit_to_directories: bool=False, |
| 85 | length_limit: int=1000): |
| 86 | """Given a directory Path object print a visual tree structure""" |
| 87 | dir_path = Path(dir_path) # accept string coerceable to Path |
| 88 | files = 0 |
| 89 | directories = 0 |
| 90 | def inner(dir_path: Path, prefix: str='', level=-1): |
| 91 | nonlocal files, directories |
| 92 | if not level: |
| 93 | return # 0, stop iterating |
| 94 | if limit_to_directories: |
| 95 | contents = [d for d in dir_path.iterdir() if d.is_dir()] |
| 96 | else: |
| 97 | contents = list(dir_path.iterdir()) |
| 98 | pointers = [tee] * (len(contents) - 1) + [last] |
| 99 | for pointer, path in zip(pointers, contents): |
| 100 | if path.is_dir(): |
| 101 | yield prefix + pointer + path.name |
| 102 | directories += 1 |
| 103 | extension = branch if pointer == tee else space |
| 104 | yield from inner(path, prefix=prefix+extension, level=level-1) |
| 105 | elif not limit_to_directories: |
| 106 | yield prefix + pointer + path.name |
| 107 | files += 1 |
| 108 | outstring = "" |
| 109 | outstring += dir_path.name + "\n" |
| 110 | iterator = inner(dir_path, level=level) |
| 111 | for line in islice(iterator, length_limit): |
| 112 | outstring += line + "\n" |
| 113 | if next(iterator, None): |
| 114 | print(f'... length_limit, {length_limit}, reached, counted:') |
| 115 | outstring += f'\n{directories} directories' + (f', {files} files' if files else '') |
| 116 | return outstring |