Skip to content

Instantly share code, notes, and snippets.

@thomasht86
Created July 3, 2025 05:53
Show Gist options
  • Select an option

  • Save thomasht86/1d8acebffeb398967f68ed8ced8af348 to your computer and use it in GitHub Desktop.

Select an option

Save thomasht86/1d8acebffeb398967f68ed8ced8af348 to your computer and use it in GitHub Desktop.
tree python
#!/usr/bin/env python3
import os
import argparse
from pathlib import Path
def walk(path: Path, prefix: str = "") -> None:
"""Recursively print a tree representation of *path*."""
# Sort so that directories appear before files, both alphabetically
entries = sorted(path.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower()))
last_idx = len(entries) - 1
for idx, entry in enumerate(entries):
connector = "└── " if idx == last_idx else "├── "
print(prefix + connector + entry.name)
if entry.is_dir():
# Choose the correct prefix for the next level
extension = " " if idx == last_idx else "│ "
walk(entry, prefix + extension)
def main() -> None:
parser = argparse.ArgumentParser(description="Python clone of the Unix tree command.")
parser.add_argument("root", nargs="?", default=".", help="Root directory (default: current)")
args = parser.parse_args()
root = Path(args.root).resolve()
print(root)
walk(root)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment