-
-
Save mplewis/6046666 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
import os | |
import sys | |
# print_compact_dir recursively prints the contents of the directory with indentation and without stuttering. | |
# If the only contents of a given directory are another single directory, that single directory is concatenated instead of indented on the next line. | |
def print_compact_dir(root, route, level, spacing=4): | |
dir_path = os.path.join(root, route) | |
contents = os.listdir(dir_path) | |
if len(contents) == 1 and os.path.isdir(os.path.join(dir_path, contents[0])): | |
# If the only content is another single directory, call self with the concatenated path instead | |
print_compact_dir(root, os.path.join(route, contents[0]), level) | |
else: | |
# Otherwise, print the route and directory contents | |
print_at_level(route + os.sep, level) | |
for dir in [item for item in contents if item[0] != '.' and os.path.isdir(os.path.join(dir_path, item))]: | |
print_compact_dir(os.path.join(root, route), dir, level+1) | |
for file in [file for file in contents if os.path.isfile(os.path.join(dir_path, item))]: | |
print_at_level(file, level+1) | |
def print_at_level(string, level): | |
if string: | |
print (' ' * spacing) * level + string | |
root = os.path.realpath(sys.argv[1]) | |
print_compact_dir(os.path.dirname(root), os.path.basename(root), 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment