Skip to content

Instantly share code, notes, and snippets.

@shwu-nyunai
Created June 20, 2024 15:49
Show Gist options
  • Save shwu-nyunai/86083001847fe3bfa2b7e304e68eaab5 to your computer and use it in GitHub Desktop.
Save shwu-nyunai/86083001847fe3bfa2b7e304e68eaab5 to your computer and use it in GitHub Desktop.
Prints tree structure given a path/str
class PrintUtils:
res = ""
@staticmethod
def DIR_KEY(x): return f'+ {x.name}/'
@staticmethod
def FILE_KEY(x): return f'- {x.name}'
@staticmethod
def make_indent(indent):
return INDENT_KEY * indent
@staticmethod
def reset_and_return() -> str:
copied_str = PrintUtils.res
PrintUtils.res = ""
return copied_str
@classmethod
def print_tree(cls, dir_path: Path, indent: int = 0):
dir_path = Path(dir_path)
_indent = cls.make_indent(indent)
if dir_path.is_file():
cls.res += _indent + cls.FILE_KEY(dir_path) + '\n'
elif dir_path.is_dir():
cls.res += _indent + cls.DIR_KEY(dir_path) + '\n'
for item in sorted(dir_path.iterdir()):
cls.res = cls.print_tree(item, indent + 1)
return cls.reset_and_return()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment