[Tutor] Using os.path.walk

Sean 'Shaleh' Perry shalehperry@home.com
Tue, 07 Aug 2001 09:00:09 -0700 (PDT)


My own hacking:

>>> def diraction(arg, dirname, names):
...     global count
...     for file in names:
...             if os.path.isfile(file):
...                     print file
...                     count = count + 1
>>> count = 0
>>> diraction(1, '.', ['foo', 'file_that_exists'])
file_that_exists
>>> count
1
>>> os.path.walk('.', diraction, None)
lots of files
>>> count
90
>>>

Hope that helps some.  The 'arg' is simply for convenience, you often want one
more piece of info in the diraction function.  If you do not use it, feel free
to pass 'None' (equiv of NULL).

count has to be global to be useful.  The only reason to assign files = names
(which does not do what you think) is if you were changing the names list. 
However, assigning foo = list just makes foo another name for list, it does not
actually copy.  For that you need foo = list[:].

Observe:

>>> l = ['foo', 'bar', 'baz']
>>> nl = l
>>> l[0]
'foo'
>>> nl[0]
'foo'
>>> nl[0] = 'wuzzy' 
>>> l[0]
'wuzzy'
>>> nl = []
>>> nl = l[:]
>>> nl[0]
'wuzzy'
>>> l[0] = 'hmmm'
>>> nl[0]
'wuzzy'