Python Dir Tree Crawling
On some system like my Linux. A Tree command is not provided by default. I have several choices:
- the find command(no indention by default, need tuning)
- ls -R(ugly by default, needs tuning)
- a Linux tree command http://mama.indstate.edu/users/ice/tree/
Python Solution
Python provides os.walk() method. A very simple pure python solution:
# -*- coding: utf-8 -*- import os path = "." def printFiles(dirList, spaceCount): for file in dirList: print "/".rjust(spaceCount+1) + file def printDirectory(dirEntry): print dirEntry[0] + "/" printFiles(dirEntry[2], len(dirEntry[0])) tree = os.walk(path) for directory in tree: printDirectory(directory)
Other Thoughts
Hmm… I believe many shell geek have their own tree script. Rakes my brain to bring indention so this is a half-way script based on ls -R:
#!/bin/bash ls -R | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
And for perl, there should be some shinning ones on CPAN. Guess ppl will use the File::Find module:
#!/usr/bin/perl use File::Find; use File::Basename; @ARGV=qw(.) if not @ARGV; find(\&do, @ARGV); sub do { $fpath=$File::Find::name; $fname=basename($fpath); print "$fname $fpath\n"; }
My perl knowledge is too limited… Have file name and dir name on same line easy for further piping…
Shhh ugly… Too much to learn!
~~
