Several months ago I wrote a post related to creating a recursive directory walker in Python. We did not make use of os.walk. While playing with Jython I thought it would be nice to write an equivalent. Here’s what I have :
from java.io import File import sys class FileWalker(object): def walk(dir,cbf): files = dir.listFiles() for file in files: cbf(file) if file.isDirectory(): FileWalker.walk(file,cbf) walk = staticmethod(walk) def list_file(file): print "saw %s" % file if __name__ == "__main__": FileWalker.walk(File(sys.argv),list_file)
I think the code is pretty straight-forward. If you’re familiar with Java even a little bit, I’m sure you can understand what’ s going on in here. You should know that the callback function isn’t receiving a string as it’s parameter ( as the first version of the walker did ) . This one receives a Java File object, which means you have access to all the methods present in the File class.