directory

James T. Dennis jadestar at idiom.com
Wed Jun 19 20:26:07 EDT 2002


Sean 'Shaleh' Perry <shalehperry at attbi.com> wrote:

> On 04-Jun-2002 Gold Fish wrote:
>> How to read the subdirectories in the directory
>> Support i have the directory /home/ which have some subdirectories
>> /home/sub1
>> /home/sub2
>> /home/sub3
>> I am using os.listdir('/home/') to read in the list so it will be 
>> ['sub1','sub2','sub3'] now i want to read inside the sub directory sub2
>> once again i using os.listdir(os.listdir('/home/')[1]) but it came out with 
>> an errors: not a file or directory. Can anyone tell me what did i wrong. 
>> Anh how to fix it.

> notice the values given by listdir('/home/') -> 'sub1', 'sub2'.  listdir()
> expects full path to a file.  You need to do
> listdir(os.path.join('/home', 'sub1')).  More likely a better option would be
> to use os.path.walk().


 os.path.walk() uses an awkward interface.  I wrote and posted this a couple
 of months ago:

#!/usr/bin/env python2.2
## Change the shebang line to match your needs!
import os
def dirwalk(startdir=None):
        if not startdir:
                startdir="."
        if not os.path.isdir(startdir):
                raise ValueError ## Is this the right exception
        stack = [startdir]
        while stack:
                cwd = stack.pop(0)
                try:
                        current = os.listdir(cwd)
                except (OSError):
                        continue
                for each in current:
                        each = os.path.join(cwd,each)
                        if os.path.islink(each):
                                pass
                        elif os.path.isdir(each):
                                stack.append(each)
                        yield(each)

if __name__ == "__main__":
        import sys
        for i in sys.argv[1:]:
                for j in dirwalk(i):
                        print j

 Notice that it implements a generator which is generally considered
 more pythonic than os.path.walk()'s "visitor" function.

 However, some people may prefer os.path.walk() or prefer a recursive
 version of dirwalk; some might prefer to make this a class, to instantiate
 directory walkers and obviate the need for the __future__ import.





More information about the Python-list mailing list