ActiveState Code

Recipe 435875: A simple non-recursive directory walker


An equivalent of os.path.walk(), but without callback function.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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.

Discussion

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).

Comments

  1. 1. At 5:28 a.m. on 1 jul 2005, Chris Cioffi said:

    os.walk() is currently preferred and non-recursive. As of Python 2.3 the os.walk() function does much the same thing and allows for selectivly choosing which directories are examined. See http://python.org/doc/2.4.1/lib/os-file-dir.html#l2h-1636

  2. 2. At 6:21 a.m. on 4 jul 2005, Sébastien Sauvage (the author) said:

    Oh... that's right. Thanks for pointing that.

Sign in to comment