Created
April 17, 2019 13:26
-
-
Save micaelbergeron/430a398d465f20204319d01d9c0147bb to your computer and use it in GitHub Desktop.
Python tree structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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