Find file functionality

Greg Jorgensen gregj at
Sat Nov 18 22:22:39 CET 2000

"Robert Gottlieb" <robert at> wrote in message
news:3a15b668.361990264 at
> Hi all,
> We are writing a tool that will need to look for the existence of a
> file in a directory hiearchy.  We need to be able to run on both
> Solaris and Windows NT.  Currently we are looking at using
> os.path.walk to crawl the tree.  The problem is that there is no way
> to tell it to stop, or at least we haven't figured that out yet.
> Does anyone know of a way to "find file" that is os generic?
> Or does anyone know how to get os.path.walk to stop once a file is
> found?

You may have to tweak this code to make it generic across platforms. It
works on my Win 2000 system.

My solution is to define a new exception type for my visit function to raise
when it finds the desired file. I hope this helps.

import exceptions
import os.path

# new exception to indicate file found
class FileFound(exceptions.Exception):
    def __init__(self, args=None):
        self.args = args

# visit function for os.path.walk
# pass name of desired file in target
def visit(target, dirname, names):
    # print dirname
    for name in names:
        path = os.path.join(dirname, name)
        # print path
        if os.path.isfile(path) and (os.path.normcase(name) == target):
            raise FileFound, path

# search disk starting at root of C drive
# target is the name of the file to look for
target = 'resume.doc'
    os.path.walk('C:\\', visit, os.path.normcase(target))
except FileFound, path:
    print "found at %s" % path

Greg Jorgensen
Deschooling Society
Portland, Oregon, USA
gregj at

More information about the Python-list mailing list