Skip to content

Commit 4d19dc5

Browse files
authored
Update PrintHierarchy.py
1 parent 48f6d75 commit 4d19dc5

File tree

1 file changed

+39
-14
lines changed

1 file changed

+39
-14
lines changed

PrintHierarchy.py

+39-14
Original file line numberDiff line numberDiff line change
@@ -7,32 +7,57 @@
77
## ---------------------------
88

99
import sys
10+
import os
1011

1112
def add_to_tree(tree, path):
1213
if len(path) == 1:
1314
tree[path[0]] = {}
1415
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="")
2225
if isinstance(v, dict):
23-
print_tree(v, level + 1)
26+
print_tree(v, level + 1, is_last, output_file)
2427

2528
def main(input_paths):
2629
tree = {}
2730

2831
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)
3257

3358
if __name__ == "__main__":
34-
# Extract input paths from command line arguments
3559
input_paths = sys.argv[1:]
36-
37-
# Call the main function with the input paths
3860
main(input_paths)
61+
62+
# Uncomment the line below to enable the test
63+
# test()

0 commit comments

Comments
 (0)