Page Actions
Wiki Actions
User Actions
Submit This Story

Python Dir Tree Crawling

On some system like my Linux. A Tree command is not provided by default. I have several choices:

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!

~~

 
blog/2009/12/python_dir_tree.txt · Last modified: 2009/12/01 00:00 (external edit)     Back to top
Recent changes RSS feed Creative Commons License Powered by PHP Driven by DokuWiki