2007-07-23

 

Python Cookbook 2.18 在给定的路径中查找文件

需求:

给定一个路径(一个目录列表,中间有分隔符分割),需要在路径中找到需要的文件.

讨论:

基本上,你需要遍历给定的路径:

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"

本节讨论的问题是很常见的问题,Python为解决它提供了很多方便.
实现搜索的循环还可以写成很多方式,但是一旦找到目标文件,就立刻返回了.在方法最后写的return None并不是必需的,因为在方法的结束是,Python默认会返回一个None.在这里写这一句是让代码看起来更清晰.

相关说明:

os.path.isfile(path)
    Test whether a path is a regular file

os.path.abspath(path)
    Return the absolute version of a path.

Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?