Generate and render a tree dynamically #44
Answered
by
pawamoy
NikosAlexandris
asked this question in
Q&A
|
Is possible in some way to dynamically generate the content for a code-block ? All of the examples in https://pawamoy.github.io/markdown-exec/usage/tree/ are static ones. I've written a small function that prints the content of a directory. Of course it can be further customised to match the expected Example ```python exec="true"
from pathlib import Path
def print_tree(directory, level=1):
directory = Path(directory)
if not directory.is_dir():
return # Ensure it's a directory
# Only list the first level of files and directories
tree = str()
for path in sorted(directory.iterdir()):
if path.name.startswith('_'):
continue # Skip files or directories starting with '_'
if path.is_dir():
tree += f"\n {path.name}/" # Add slash to indicate it's a directory
else:
tree += f"\n {path.name}"
# Optionally print a trailing line after listing
if level == 1:
tree += '\n '
return tree
tree = print_tree('api/')
print(f"```\n{tree}\n```")
``` |
Answered by
pawamoy
Apr 21, 2024
Replies: 2 comments 1 reply
So, does it work 🙂? Instead of using |
0 replies
Answer selected by
pawamoy
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

So, does it work 🙂?
Instead of using
print(f"```\n{tree}\n```")I think you can simply print the tree without fences, and addresult="tree"to your code block options.