Created
November 27, 2021 10:13
-
-
Save linuskmr/8f5d0ce4f15106942d965c5b94a95a51 to your computer and use it in GitHub Desktop.
Single python function for generating ASCII trees
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data = [ | |
'Desktop', | |
('Downloads', [ | |
'ubuntu.iso', | |
'abc.txt', | |
('photos', [ | |
'001.jpg', | |
'002.jpg' | |
]) | |
]) | |
] | |
def ascii_tree(tree, indent: int = 0) -> str: | |
tree_str = '' | |
def add_to_tree_str(x): | |
nonlocal tree_str | |
tree_str += f"{indent * '│ '}├─ {x}\n" | |
if isinstance(tree, tuple): | |
add_to_tree_str(tree[0]) | |
tree_str += ascii_tree(tree[1], indent + 1) | |
elif isinstance(tree, list): | |
for item in tree: | |
tree_str += ascii_tree(item, indent) | |
else: | |
add_to_tree_str(tree) | |
return tree_str | |
print(ascii_tree(data)) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
├─ Desktop | |
├─ Downloads | |
│ ├─ ubuntu.iso | |
│ ├─ abc.txt | |
│ ├─ photos | |
│ │ ├─ 001.jpg | |
│ │ ├─ 002.jpg |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment