Find file functionality

Fredrik Lundh fredrik at effbot.org
Sun Nov 19 02:45:15 EST 2000


Robert Gottlieb wrote:
> Or does anyone know how to get os.path.walk to stop once a file is
> found?

the docs mention that you can modify the directory list:

    "The visit function may modify names to influence the
    set of directories visited below dirname, e.g., to avoid
    visiting certain parts of the tree. (The object referred
    to by names must be modified in place, using del or
    slice assignment.)

:::

if you need to stop on an individual file, you can raise an
exception instead (e.g. EOFError)

    def func(arg, dirname, names):
        for file in names:
            if something(file):
                raise EOFError

    try:
        os.path.walk(...)
    except EOFError:
        print "found it"

:::

a third alternative is to forget about walk, and use a directory
walker object instead.  here's an example from the eff-bot guide
to the standard library:

# os-path-walk-example-3.py
# from (the eff-bot guide to) The Python Standard Library
# http://www.pythonware.com/people/fredrik/librarybook.htm

import os

class DirectoryWalker:

    def __init__(self, directory):
        self.stack = [directory]
        self.files = []
        self.index = 0

    def __getitem__(self, index):
        while 1:
            try:
                file = self.files[self.index]
                self.index = self.index + 1
            except IndexError:
                # pop next directory from stack
                self.directory = self.stack.pop()
                self.files = os.listdir(self.directory)
                self.index = 0
            else:
                # got a filename
                fullname = os.path.join(self.directory, file)
                if os.path.isdir(fullname) and not os.path.islink(fullname):
                    self.stack.append(fullname)
                return fullname

for file in DirectoryWalker("."):
    print file
    if something(file):
        break

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list