Created
December 21, 2012 06:31
-
-
Save sosukeinu/4351054 to your computer and use it in GitHub Desktop.
PYTHON Simple 'Unix Tree' script
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
import os | |
import sys | |
def getroot(): | |
# If the length of 'sys.argv' is longer than one, index 1 is assumed to be | |
# root. | |
if len(sys.argv) == 1: | |
path = '' | |
else: | |
path = sys.argv[1] | |
# If 'path' is root, it becomes 'tree_root'. If 'path' is not root, | |
# 'tree_root' becomes the current working directory. 'os.path.join' | |
# concatenates a '/' onto the end of cwd. | |
if os.path.isabs(path): | |
tree_root = path | |
else: | |
tree_root = os.path.join(os.getcwd(), path) | |
return tree_root | |
def getdirlist(path): | |
# Returns all files and directories in 'path' as a ordered list of strings. | |
dirlist = os.listdir(path) | |
dirlist.sort() | |
return dirlist | |
def traverse(path, prefix = '|--', s = '.\n', f = 0, d = 0): | |
# Gets an ordered list of files in the cwd as strings. | |
dirlist = getdirlist(path) | |
# Concatenates everything to 's' to be printed as the tree | |
for num, file in enumerate(dirlist): | |
lastprefix = prefix[:-3] + '`--' | |
dirsize = len(dirlist) | |
if num < dirsize - 1: | |
# Prints as follows: '|-- stupid.py' | |
s += '%s %s\n' % (prefix, file) | |
else: | |
s += '%s %s\n' % (lastprefix, file) | |
# 'path2file' becomes the address to the file | |
path2file = os.path.join(path, file) | |
# a recursive call is ran if the file is a directory | |
if os.path.isdir(path2file): | |
d += 1 | |
if getdirlist(path2file): | |
s, f, d = traverse(path2file, '| ' + prefix, s, f, d) | |
else: | |
f += 1 | |
return s, f, d | |
if __name__ == '__main__': | |
#root = getroot() | |
root = '/home/timejr/temp/' | |
tree_str, files, dirs = traverse(root) | |
if dirs == 1: | |
dirstring = 'directory' | |
else: | |
dirstring = 'directories' | |
if files == 1: | |
filestring = 'file' | |
else: | |
filestring = 'files' | |
# prints the Unix tree and how many files and directories there are | |
print tree_str | |
print '%d %s, %d %s' % (dirs, dirstring, files, filestring) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment