Get the filenames in a directory and its subdirectories

Fredrik Lundh fredrik at pythonware.com
Sun Jun 29 17:23:13 EDT 2003


"Psymaster" wrote:

> That would be very handy for a small progrtam I've written. I've
> browsed through the documentation for the standard modules but
> there doesn't seem to be a way (please correct me if I'm wrong).

os.path.walk (with a rather weird interface; look it up in the docs)

> I know that it shouldn't be very hard to write a module myself
> using listdir() and isdir() or stuff like that, but I'm having  problems.

here's a simple version; if you want, you can change it into
a generator (use yield to return the names, instead of adding
them to one big list), but it's perfectly usable as is [1]:

def listdir(root, path=""):
    # recursive listdir
    files = []
    try:
        for file in os.listdir(os.path.join(root, path)):
            pathname = os.path.join(path, file)
            if os.path.isdir(os.path.join(root, pathname)):
                files.extend(listdir(root, pathname))
            else:
                files.append(pathname)
    except OSError:
        pass
    return files

you may also want to take a look at the os.path examples in
my library book:

    http://effbot.org/zone/librarybook-index.htm
    => core modules, page 1-35ff

</F>

1) unless I messed something up when posting it, of course.








More information about the Python-list mailing list