A simple non-recursive directory walker in Python

By chris

This is taken from here:

A simple directory walker, without the burden of creating a callback for os.path.walk().

This is also usefull for incremental directory walking (where you want to scan remaining directories in subsequent calls).

import os, os.path

startDir = "/"

directories = [startDir]
while len(directories)>0:
    directory = directories.pop()
    for name in os.listdir(directory):
        fullpath = os.path.join(directory,name)
        if os.path.isfile(fullpath):
            print fullpath                # That's a file. Do something with it.
        elif os.path.isdir(fullpath):
            directories.append(fullpath)  # It's a directory, store it.

2 Responses to “A simple non-recursive directory walker in Python”

  1. della Says:

    Why not just using os.walk(), as the comments in the linked page say?

  2. chris Says:

    Because I didn’t have time to read the comments… ;)

Leave a Reply