Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1from pathlib import Path 

2from typing import Union 

3import sys 

4# prefix components: 

5space = ' ' 

6branch = '│ ' 

7# pointers: 

8tee = '├── ' 

9last = '└── ' 

10headline_high_start = '┌' 

11headline_low_start = '└' 

12headline_body = '─' 

13headline_high_end = '┐' 

14headline_low_end = '┘' 

15headline_sides = '│' 

16 

17 

18def tree(dir_path: Path, prefix: str = ' '): 

19 """A recursive generator, given a directory Path object 

20 will yield a visual tree structure line by line 

21 with each line prefixed by the same characters 

22 """ 

23 

24 contents = list(dir_path.iterdir()) 

25 # contents each get pointers that are ├── with a final └── : 

26 pointers = [tee] * (len(contents) - 1) + [last] 

27 for pointer, path in zip(pointers, contents): 

28 yield prefix + pointer + path.name 

29 if path.is_dir(): # extend the prefix and recurse: 

30 extension = branch if pointer == tee else space 

31 # i.e. space because last, └── , above so no more | 

32 yield from tree(path, prefix=prefix + extension) 

33 

34 

35def create_tree(dir_path: Path, prefix: str = ' ', category=None): 

36 name = 'Name: ' + dir_path.name 

37 if category is not None: 

38 category = 'Category: ' + category.upper() 

39 length_name = max([len(name), len(category)]) 

40 length_dif = length_name - min([len(name), len(category)]) 

41 else: 

42 length_name = len(name) 

43 yield headline_high_start + headline_body * length_name + headline_high_end 

44 if category is not None and len(name) < len(category): 

45 yield headline_sides + name + ' ' * length_dif + headline_sides 

46 else: 

47 yield headline_sides + name + headline_sides 

48 if category is not None: 

49 if len(category) < len(name): 

50 yield headline_sides + category + ' ' * length_dif + headline_sides 

51 else: 

52 yield headline_sides + category + headline_sides 

53 yield headline_low_start + headline_body * length_name + headline_low_end 

54 yield from tree(dir_path, prefix) 

55 

56 

57def print_tree(dir_path: Union[Path, str], category=None, output_function=print): 

58 if isinstance(dir_path, str): 

59 dir_path = Path(dir_path) 

60 for line in create_tree(dir_path, ' ', category): 

61 output_function(line) 

62 

63 

64if __name__ == '__main__': 

65 print_tree(sys.argv[1])