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.
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')
You might find http://code.activestate.com/recipes/499305/ interesting.