文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 218.25.66.198 [DateTime(2004-09-29T04:24:34Z)] TableOfContents

描述

Finding a File Given an Arbitrary 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 whose name is as requested.

解决 Solution

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

import os, string

def search_file(filename, search_path, pathsep=os.pathsep):

if _ _name_ _ == '_ _ _main_ _':

讨论 Discussion

This is a reasonably frequent task, and Python makes it extremely easy. The search loop can be coded in many ways, but returning the normalized path 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 what Python returns when a function falls off the end, but having the return explicit in this case makes the functionality of search_file much clearer at first sight.

To find files specifically on Python's own search path, see Recipe 4.22.

参考 See Also

Recipe 4.22; documentation for the module os in the Library Reference.