Last active
February 24, 2020 12:45
-
-
Save jvrplmlmn/5755890 to your computer and use it in GitHub Desktop.
Python implementation of tree command
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
# -*- coding: utf-8 -*- | |
from os import walk, sep | |
from os.path import basename, isdir | |
from sys import argv | |
def tree(startpath, print_files=False): | |
for root, subdirs, files in walk(startpath): | |
level = root.replace(startpath, '').count(sep) | |
indent = ' |' * (level-1) + ' +- ' | |
print "%s%s/" % (indent, basename(root)) | |
#print "{}{}/".format(indent, os.path.basename(root)) | |
subindent = ' |' * (level) + ' +- ' | |
if print_files: | |
for f in files: | |
print "%s%s" % (subindent, f) | |
#print "{}{}/".format(subindent, f) | |
def usage(): | |
return '''Usage: %s [-h] [-f] [PATH] | |
Print tree structure. | |
Options: | |
-h, --help Print help info | |
-f Print files as well as directories | |
PATH Path to process''' % basename(argv[0]) | |
def main(): | |
path = '.' | |
# Check for help | |
if ('-h' or '--help') in argv: | |
print usage() | |
# tree | |
elif len(argv) == 1: | |
tree(path) | |
# tree -f | |
elif len(argv) == 2 and argv[1] == '-f': | |
tree(path, True) | |
# tree dir | |
elif len(argv) == 2: | |
path = argv[1] | |
if isdir(path): | |
tree(path) | |
else: | |
print 'ERROR: \'' + path + '\' is not a directory' | |
# tree -f dir | |
elif len(argv) == 3 and argv[1] == '-f': | |
path = argv[2] | |
if isdir(path): | |
tree(path, True) | |
else: | |
print 'ERROR: \'' + path + '\' is not a directory' | |
else: | |
print 'ERROR: Wrong parameters' | |
print usage() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For what's worth, here is an implementation leveraging
treelib
. Of course less efficient, but can be interesting. https://gist.github.com/smarie/3536eab83994b993324b85046bb237b4