Recipe2.18.Finding a File Given a Search Path


Recipe 2.18. Finding a File Given a Search Path

Credit: Chui Tey

Problem

Given a search path (a string of directories with a separator in between), you need to find the first file along the path with the requested name.

Solution

Basically, you need to loop over the directories in the given search path:

import os def search_file(filename, search_path, pathsep=os.pathsep):     """ Given a search path, find file with requested name """     for path in search_path.split(pathsep):         candidate = os.path.join(path, filename)         if os.path.isfile(candidate):             return os.path.abspath(candidate)     return None if _ _name_ _ == '_ _main_ _':     search_path = '/bin' + os.pathsep + '/usr/bin'  # ; on Windows, : on Unix     find_file = search_file('ls', search_path)     if find_file:         print "File 'ls' found at %s" % find_file     else:         print "File 'ls' not found"

Discussion

This recipe's "Problem" is a reasonably frequent task, and Python makes resolving it extremely easy. Other recipes perform similar and related tasks: to find files specifically on Python's own search path, see Recipe 2.20; to find all files matching a pattern along a search path, see Recipe 2.19.

The search loop can be coded in many ways, but returning the path (made into an absolute path, for uniformity and convenience) as soon as a hit is found is simplest as well as fast. The explicit return None after the loop is not strictly needed, since None is returned by Python when a function falls off the end. Having the return statement explicitly there in this case makes the functionality of search_file much clearer at first sight.

See Also

Recipe 2.20; Recipe 2.19; documentation for the module os in the Library Reference and Python in a Nutshell.



Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2004
Pages: 420

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net