Welcome, guest | Sign In | My Account | Store | Cart

Walks subdirectories to find a file and returns . Default start location is the current working directory. Optionally, a different directory can be set as the search's starting location.

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import os

def findInSubdirectory(filename, subdirectory=''):
    if subdirectory:
        path = subdirectory
    else:
        path = os.getcwd()
    for root, dirs, names in os.walk(path):
        if filename in names:
            return os.path.join(root, filename)
    raise 'File not found'

I initially wrote findInSubdirectory to make it more convenient to pass in data files to python scripts from the command line. Specifically,

# Create parser for command line options
parser = OptionParser()

# Get filename/resolve path
parser.add_option("-f", "--file", dest="filename", type="string",
                  help="Specifies log file", metavar="FILE")

parser.add_option("-s", "--subdirectory", dest="subdirectory", type="string",
                help="Specifies path to logfile", metavar="subdirectory")

subdirectory = options.subdirectory
filename = options.filename

path_to_file = findInSubdirectory(filename, subdirectory)
logData = open(path_to_file, 'r')

1 comment

Simon Brunning 14 years, 1 month ago  # | flag

You might find http://code.activestate.com/recipes/499305/ interesting.

Created by Daniel Cohn on Tue, 2 Feb 2010 (MIT)
Python recipes (4591)
Daniel Cohn's recipes (6)

Required Modules

Other Information and Tasks