[Tutor] os.path.walk

Kent Johnson kent37 at tds.net
Tue Aug 22 13:19:48 CEST 2006


nimrodx wrote:
> Hi All,
>
> I was wondering if anyone had used os.path.walk within a class or not, 
> and what are the pitfalls...
>
> What has got me worried is that the function called by os.path.walk  
> must be a method of the class.
> Now this means it will have something like this as a def:
>
> def func_called_by_walk(self, arg, directory, names):
>
> Will this work with os.path.walk with that definition?

Yes, that is the right way to do it and it will work fine. Something like

class Walker(object):
  def walk(self, base):
    os.path.walk(base, self.callback, None)

  def callback(self, arg, dir, names):
    pass

What happens is, when Python looks up self.callback it converts the 
method to a "bound method". The bound method is a a callable that takes 
(in this case) only three arguments; the value of self is held by the 
bound method and passed to the original function object (which does take 
four arguments).

But, if you are using a recent version of Python (2.3 or greater) you 
should look at os.walk(), it is easier to use than os.path.walk().

Kent



More information about the Tutor mailing list