directory listing

Fredrik Lundh fredrik at pythonware.com
Fri Nov 11 16:37:39 EST 2005


"SU News Server" <mkonrad at syr.edu> wrote:

> I've struggled with this for quite a while and I'm am just not sure
> what is going on. I have the following code
> import os
>
> def buildList( directory='/Users/mkonrad' )
>
> dirs = [ ]
>
> listing = os.listdir(directory)
>
> for x in listing:
>       if os.path.isdir(x):
>            dirs.append(x)
>
> return dirs
>
> This always returns an empty list.
> Now if I change it so that directory='.' or directory=os.getcwd()
> Then it returns a list of directories.

hint: if you're not sure what's going on in your program, adding
a print statement or two is an easy way to figure it out.  like, say:

    for x in listing:
        print x
        if os.path.isdir(x):
            dirs.append(x)

(try this before you continue)

   :
   :
   :

the problem is that os.listdir returns a list of filenames, without
the preceeding directory name.  you can add an os.path.join

    for x in listing:
        x = os.path.join(directory, x)
        if os.path.isdir(x):
            dirs.append(x)

or use the glob module instead:

    listing = glob.glob(os.path.join(directory, "*"))

hope this helps!

</F>






More information about the Python-list mailing list