Skip to content

Instantly share code, notes, and snippets.

@jaredyam
Created November 7, 2020 05:15
Show Gist options
  • Select an option

  • Save jaredyam/5f0228f48e1ff7a4bd28ae668a6a646e to your computer and use it in GitHub Desktop.

Select an option

Save jaredyam/5f0228f48e1ff7a4bd28ae668a6a646e to your computer and use it in GitHub Desktop.
"""Print out the current directory's tree structure to console.
Inspired by the `colorls --tree` command from the open source codebase Colorls
references
----------
https://github.com/athityakumar/colorls/blob/a7006a5fd3eba6945ee29a499e4db72bdcc26114/lib/colorls/core.rb#L351
"""
from pathlib import Path
def tree_traverse(path, prespace, depth, indent):
entries = sorted((i for i in path.glob('[!.]*')), key=lambda x: is_dir(x))
for i, entry in enumerate(entries):
icon = ' └──' if i == len(entries) - 1 or entry.is_dir() else ' ├──'
print(tree_branch_preprint(prespace, indent, icon),
entry.name + '/' if entry.is_dir() else entry)
if entry.is_dir():
tree_traverse(entry,
prespace + indent,
depth + 1,
indent)
def is_dir(path):
return 'dir' if path.is_dir() else 'file'
def tree_branch_preprint(prespace, indent, prespace_icon):
return prespace_icon if prespace == 0 else ' │ ' * (prespace // indent) + prespace_icon
if __name__ == '__main__':
dirpath = Path('.')
print(dirpath.cwd().name + '/')
tree_traverse(Path(dirpath.name), 0, 1, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment