tags:

views:

141

answers:

3

I have a file that may be in a different place on each user's machine. Is there a way to implement a search for the file? A way that I can pass the file's name and the directory tree to search in?

A: 

See the os module for os.walk or os.listdir

See also this question http://stackoverflow.com/questions/229186/os-walk-without-digging-into-directories-below for sample code

Martin Beckett
+1  A: 

hopefully this helps

rabbit
Welcome to SO and an excellent first answer!
Martin Beckett
+10  A: 

os.walk is the answer, this will find the first match:

import os

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)

And this will find all matches:

def find_all(name, path):
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(root, name))
    return result

And this will match a pattern:

import os, fnmatch
def find(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result

find('*.txt', '/path/to/dir')
Nadia Alramli