Find file functionality

Greg Jorgensen gregj at pobox.com
Sat Nov 18 16:22:39 EST 2000


"Robert Gottlieb" <robert at webwarecorp.com> wrote in message
news:3a15b668.361990264 at news.earthlink.net...
> 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
            break

# search disk starting at root of C drive
# target is the name of the file to look for
target = 'resume.doc'
try:
    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 pobox.com





More information about the Python-list mailing list