Created
November 1, 2015 02:31
-
-
Save macro1/17c85e26ecb25b9169f3 to your computer and use it in GitHub Desktop.
Reimplementation of basic Unix-style tree command in Python.
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
#! /usr/bin/env python | |
"""Reimplementation of basic Unix-style tree command in Python 3.""" | |
import argparse | |
from os import listdir, path | |
def print_tree(top, prefix=''): | |
print('{prefix}{base_name}'.format( | |
prefix=prefix, base_name=path.basename(top))) | |
prefix = prefix.replace('└──', ' ').replace('├──', '| ') | |
try: | |
children = listdir(top) | |
except OSError as e: | |
return | |
children = sorted(children) | |
for name in children[:-1]: | |
print_tree(path.sep.join([top, name]), | |
prefix='{prefix}├── '.format(prefix=prefix)) | |
if children: | |
print_tree(path.sep.join([top, children[-1]]), | |
prefix='{prefix}└── '.format(prefix=prefix)) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('directory') | |
args = parser.parse_args() | |
print_tree(args.directory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment