Source

scripts / dirtree.py

Full commit
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
A simple script for printing directory trees.

2007-2008 (c) Andy Mikhailenko

CHANGELOG:
	2007-06-23	basic two-liner script
	2008-01-27	+argument processing ('--dir' and '--short')
"""

import sys
import getopt
import os

ROOT_DIR       = os.getcwd()
SHOW_FULL_PATH = True
SHOW_FILES     = False
SHOW_HIDDEN    = False

def show_usage():
	print """
NAME
       dirtree.py - a simple recursive directory listing script

SYNOPSIS
       dirtree [OPTION]

OPTIONS
       Show directories tree

       -h, --help
              displays this message

       -d DIRECTORY, --dir=DIRECTORY
              set root directory to DIRECTORY (by default it's current working directory)

       -s, --short
              do not show full path

       -f, --files
              show files

       -a, --all
              do not skip hidden directories and/or files

AUTHOR
       Written by Andy Mikhailenko."""

# Process the arguments, tune our behaviour

try:
	opts, args = getopt.getopt(sys.argv[1:],'sd:fah',['short','dir=','files','all','help'])
except getopt.GetoptError, e:
	print e
	show_usage()
	sys.exit()
for opt, arg in opts:
	if opt in ('-h', '--help'):
		show_usage()
		sys.exit()
	elif opt in ('-d','--dir'):
		ROOT_DIR = arg
	elif opt in ('-s','--short'):
		SHOW_FULL_PATH = False
	elif opt in ('-f','--files'):
		SHOW_FILES = True
	elif opt in ('-a','--all'):
		SHOW_HIDDEN = True

# Walk and report

for root, dirs, files in os.walk(ROOT_DIR):
	path = root
	local_path = path.replace(ROOT_DIR,'')
	if not SHOW_FULL_PATH:
		if path == ROOT_DIR:
			path = ''
		else:
			path = local_path
	if '/.' in local_path and not SHOW_HIDDEN:
		continue
	if path:
		print '%s/' % path	#.replace('\\','/')
	if SHOW_FILES:
		for f in sorted(files):
			if f.startswith('.') and not SHOW_HIDDEN:
				continue
			if path:
				print '%s/%s' % (path,f)
			else:
				print f