Skip to content

Instantly share code, notes, and snippets.

@micaelbergeron
Created April 17, 2019 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micaelbergeron/430a398d465f20204319d01d9c0147bb to your computer and use it in GitHub Desktop.
Save micaelbergeron/430a398d465f20204319d01d9c0147bb to your computer and use it in GitHub Desktop.
Python tree structure
cat dirtree.py
#!/bin/python
import os
import sys
import fileinput
import enum
class EntryType(enum.Enum):
FILE = "f"
DIR = "d"
def parse(value: str):
# count number of leading spaces
space = 0
for c in value:
if c != " ":
break;
space += 1;
t, *entry = value.strip().split(":")
if len(entry) == 0:
t = EntryType.DIR
entry = [value]
else:
t = EntryType(t)
return t, ":".join(entry).strip(), int(space/2)
def main(args):
for line in fileinput.input():
t, entry, indent = parse(line)
tree_mark = ""
if indent:
for i in range(indent - 1):
tree_mark += "| "
tree_mark += "├── "
dir_mark = "/" if t is EntryType.DIR else ""
print(f"{tree_mark}{entry}{dir_mark}")
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment