Skip to content

Instantly share code, notes, and snippets.

@diabycode
Created February 6, 2024 14:05
Show Gist options
  • Save diabycode/8a11afbaf0f14617274215a9af9af6b8 to your computer and use it in GitHub Desktop.
Save diabycode/8a11afbaf0f14617274215a9af9af6b8 to your computer and use it in GitHub Desktop.
Windows 'tree' command implemented in python
from pathlib import Path
import argparse
import sys
DEFAULT_PATH = "."
def get_tree(p: Path, root_path: Path, f:bool=False) -> None:
"""Get the tree structure of a directory
args:
p: Path -> path to get structure for
root_path: Path -> the main path
f: Bool -> include files or not
"""
for i in p.glob("*"):
level = len(i.relative_to(root_path).parts)
name = i.name + "/" if i.is_dir() else i.name
tab = "|___" * level
line = f"{tab}+ {name}"
if f:
print(line)
if not f and i.is_dir():
print(line)
if i.is_dir():
get_tree(p=i, root_path=root_path, f=f)
def cli():
""" Manage cli's inputs """
parser = argparse.ArgumentParser(
prog="Pytree",
description="Show the tree structure of a directory")
parser.add_argument("-p", "--path", help="Path to get the structure", dest="path")
parser.add_argument("-f", "--file", help="Show files", action="store_true", dest="show_file")
return parser.parse_args()
def main():
"""Main prog"""
args = cli()
path = Path(args.path) if args.path else Path(DEFAULT_PATH)
if not path.exists():
print(f"Error : path not found '{path}'")
sys.exit(1)
print(f"{path.resolve()}/")
get_tree(p=path, f=args.show_file, root_path=path)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment