from collections import defaultdict
import os
# Build the directory tree
root_dir = 'Desktop'
files = [
'meetings/2021-01-12/notes.txt',
'meetings/2020_calendar.ods',
'meetings/2021-01-12/report.pdf',
'misc/photos/forest_20130430.jpg',
'misc/photos/sunset_20130412.jpg',
'scripts/tree.py',
'meetings/2021-01-24/report.pdf',
]
# Helper function to add files to the directory tree
def add_to_tree(root, path_parts):
current = root
for part in path_parts[:-1]:
if part not in current:
current[part] = {}
current = current[part]
# Add the file at the end
current[path_parts[-1]] = None
# def show(root_dir, files):
# _tree = {}
# for file in files:
# f = f"{root_dir}/{file}"
# parts = file.split('/')
# add_to_tree(_tree, parts)
# def show_tree(tr, lvl=0, end=False):
# ans = '\n'
# if isinstance(tr, dict):
# keys = sorted([k for k in tr.keys()], key=lambda x: (tr[x] is None, x))
# for i in range(len(keys)):
# print(keys, i == len(keys) - 1)
# ans += ("│ " + " " * (lvl - 1) if end else "│ " * lvl) + f"{'├' if i != len(keys) - 1 else '└'}── {keys[i]}" + show_tree(tr[keys[i]], lvl + 1, i == len(keys) - 1)
# return ans
# return "".join([root_dir, show_tree(_tree)])
# # Print the directory tree
# print(show(root_dir, files))
paths = {}
for file in files:
f = f"{root_dir}/{file}"
parts = file.split('/')
add_to_tree(paths, parts)
print(paths)
# prefix components:
space = ' '
branch = '│ '
# pointers:
tee = '├── '
last = '└── '
def _tree(paths: dict, prefix: str = ''):
"""A recursive generator, given a directory Path object
will yield a visual tree structure line by line
with each line prefixed by the same characters
"""
# contents each get pointers that are ├── with a final └── :
pointers = [tee] * (len(paths) - 1) + [last]
for pointer, path in zip(pointers, sorted(paths, key=lambda x: (paths[x] is None, x))):
yield prefix + pointer + path
if isinstance(paths[path], dict): # extend the prefix and recurse:
extension = branch if pointer == tee else space
# i.e. space because last, └── , above so no more |
yield from _tree(paths[path], prefix=prefix+extension)
def tree(root, paths):
ans = [root]
for p in _tree(paths):
ans.append(p)
return '\n'.join(ans)
r = tree(root_dir, paths)
print(r)
To embed this program on your website, copy the following code and paste it into your website's HTML: