Skip to content

Instantly share code, notes, and snippets.

@taylortrimble
Last active December 20, 2015 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save taylortrimble/6046652 to your computer and use it in GitHub Desktop.
Save taylortrimble/6046652 to your computer and use it in GitHub Desktop.
cdid.py 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.
#!/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):
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 is_dir(dir_path, item) and not is_hidden(item)]:
print_compact_dir(os.path.join(root, route), dir, level+1)
for hidden_dir in [item for item in contents if is_dir(dir_path, item) and is_hidden(item)]:
print_at_level(hidden_dir + os.sep, level+1)
for file in [item for item in contents if not is_dir(dir_path, item) and not is_hidden(item)]:
print_at_level(file, level+1)
def print_at_level(string, level):
if string:
print " " * level + string
def is_hidden(file):
return file[0] == '.'
def is_dir(dir_path, file):
return os.path.isdir(os.path.join(dir_path, file))
if len(sys.argv) == 2:
root = os.path.realpath(sys.argv[1])
elif len(sys.argv) == 1:
root = os.getcwd()
else:
print "usage: cdir [root_dir]"
exit(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