Skip to content

Instantly share code, notes, and snippets.

@mplewis
Forked from taylortrimble/cdir.py
Created July 20, 2013 22:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mplewis/6046666 to your computer and use it in GitHub Desktop.
Save mplewis/6046666 to your computer and use it in GitHub Desktop.
#!/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