Generate and render a tree dynamically #44
-
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```")
``` |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
So, does it work 🙂? Instead of using |
Beta Was this translation helpful? Give feedback.
-
Yes, it does and your library is Awesome. ps- And I need to fix my function to work properly :D. |
Beta Was this translation helpful? Give feedback.
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.