os module - reliable?

Steven Adams quickdry at users.sourceforge.net
Sun Dec 31 01:01:50 EST 2000


<curtissol at my-deja.com> wrote in message
news:92m38n$88f$1 at nnrp1.deja.com...
> I am writing exercise 1 pg 212 of "Learning Python". It asks for a
> program that prints out the names of all files in a specific
directory
> and all its subdirectories. The code I have seems relatively
straight
> forward:
>
> import os, sys
>
> def ShowDirContents(dir):
>     contents = os.listdir(dir)
>
>     for file in contents:
>         if os.path.isdir(file):
>             ShowDirContents(file)
>         else:
>             print file

your code isn't updating what it uses as a new directory to search
through, sometimes it helps to trace through your code exactly what
variable changes to what value, and where, listdir() gives out only
the filename, not its absolute path.

change ShowDirContents(dir) to this and it should be fine - the code
you have doesn't need sys either.

def ShowDirContents(dir):
            for file in os.listdir(dir):
                if os.path.isdir(dir+os.sep+file):
                    ShowDirContents(dir+os.sep+x)
                else:
                    print file

hope that helps,

Steven





More information about the Python-list mailing list