|
7 | 7 | ## ---------------------------
|
8 | 8 |
|
9 | 9 | import sys
|
| 10 | +import os |
10 | 11 |
|
11 | 12 | def add_to_tree(tree, path):
|
12 | 13 | if len(path) == 1:
|
13 | 14 | tree[path[0]] = {}
|
14 | 15 | else:
|
15 |
| - if path[0] not in tree: |
16 |
| - tree[path[0]] = {} |
17 |
| - add_to_tree(tree[path[0]], path[1:]) |
18 |
| - |
19 |
| -def print_tree(tree, level=0): |
20 |
| - for k, v in tree.items(): |
21 |
| - print(" " * level + k) |
| 16 | + add_to_tree(tree.setdefault(path[0], {}), path[1:]) |
| 17 | + |
| 18 | +def print_tree(tree, level=0, is_last=False, output_file=None): |
| 19 | + prefix = "| " * (level - 1) + "|-- " if level > 0 else "" |
| 20 | + for i, (k, v) in enumerate(tree.items()): |
| 21 | + is_last = i == len(tree) - 1 |
| 22 | + line = f"{prefix}{k}\n" |
| 23 | + output_file.write(line) |
| 24 | + print(line, end="") |
22 | 25 | if isinstance(v, dict):
|
23 |
| - print_tree(v, level + 1) |
| 26 | + print_tree(v, level + 1, is_last, output_file) |
24 | 27 |
|
25 | 28 | def main(input_paths):
|
26 | 29 | tree = {}
|
27 | 30 |
|
28 | 31 | for path in input_paths:
|
29 |
| - add_to_tree(tree, path.split("/")) |
30 |
| - |
31 |
| - print_tree(tree) |
| 32 | + if os.path.exists(path): |
| 33 | + add_to_tree(tree, path.split("/")) |
| 34 | + else: |
| 35 | + print(f"Warning: File or directory '{path}' does not exist.") |
| 36 | + |
| 37 | + home_dir = os.path.expanduser("~") |
| 38 | + output_file_path = os.path.join(home_dir, "tree_output.txt") |
| 39 | + |
| 40 | + with open(output_file_path, "w") as output_file: |
| 41 | + print_tree(tree, output_file=output_file) |
| 42 | + |
| 43 | + print(f"Tree output saved to: {output_file_path}") |
| 44 | + |
| 45 | +def test(): |
| 46 | + home_dir = os.path.expanduser("~") |
| 47 | + home_tree = {"~": {}} |
| 48 | + for root, dirs, files in os.walk(home_dir): |
| 49 | + curr_dir = root.replace(home_dir, "~") |
| 50 | + parent_dir = os.path.dirname(curr_dir) |
| 51 | + add_to_tree(home_tree.setdefault(parent_dir, {}), [os.path.basename(curr_dir)]) |
| 52 | + for file in files: |
| 53 | + add_to_tree(home_tree.setdefault(curr_dir, {}), [file]) |
| 54 | + |
| 55 | + print("Home Folder Hierarchy:") |
| 56 | + print_tree(home_tree) |
32 | 57 |
|
33 | 58 | if __name__ == "__main__":
|
34 |
| - # Extract input paths from command line arguments |
35 | 59 | input_paths = sys.argv[1:]
|
36 |
| - |
37 |
| - # Call the main function with the input paths |
38 | 60 | main(input_paths)
|
| 61 | + |
| 62 | + # Uncomment the line below to enable the test |
| 63 | + # test() |
0 commit comments