文章来自《Python cookbook》.

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

-- 218.25.66.198 [2004-09-29 04:24:34]

1. 描述

Finding a File Given an Arbitrary Search Path

在任意的搜索路径(集合)下,查找文件 Credit: Chui Tey

1.1. 问题 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.

给定搜索路径(分隔符分开的欲搜索路径组成的字符串),查找第一个名称符合的文件。

1.2. 解决 Solution

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

一般来说,需要在给定的搜索路径集合上循环:

   1 import os, string
   2 
   3 def search_file(filename, search_path, pathsep=os.pathsep):
   4     """ Given a search path, find file with requested name """
   5     for path in string.split(search_path, pathsep):
   6         candidate = os.path.join(path, filename)
   7         if os.path.exists(candidate): return os.path.abspath(candidate)
   8     return None
   9 
  10 if _ _name_ _ == '_ _ _main_ _':
  11     search_path = '/bin' + os.pathsep + '/usr/bin'  # ; on Windows, : on Unix
  12     find_file = search_file('ls',search_path)
  13     if find_file:
  14         print "File found at %s" % find_file
  15     else:
  16         print "File not found"

1.3. 讨论 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.

这是一个很常见的任务,使用Python处理变得特简单。 循环语句可以采用很多风格实现,但是最简单又快速的方法是:发现一个符合条件文件立即返回它的规范化的路径。脚本中循环后面明确返回的None不是严格必需的,Python中函数没有返回值,默认返回一个None。不过,这里明确返回None,使得代码(查找的)功能一眼就可以看得更清楚些。

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

在Python的运行时搜索路径上查找文件,参见食谱 4.22 http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d4_2d22

1.4. 参考 See Also

食谱4.22 http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d4_2d22;

Python 文档os模块部分