Skip to content

Instantly share code, notes, and snippets.

@linuskmr
Created November 27, 2021 10:13
Show Gist options
  • Save linuskmr/8f5d0ce4f15106942d965c5b94a95a51 to your computer and use it in GitHub Desktop.
Save linuskmr/8f5d0ce4f15106942d965c5b94a95a51 to your computer and use it in GitHub Desktop.
Single python function for generating ASCII trees
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))
├─ 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