2007-07-25

 

Python Cookbook 2.20 在Python搜索路径中查找文件

需求:

一个很大的Python应用,引用了很多资源文件(比如:项目文件,SQL脚本,图片等),你希望将它们放到一起,以便打包.

讨论:

需要在Python搜索路径中查找,该路径保存在sys.path中:

import sys, os
class Error(Exception): pass
def _find(pathname, matchFunc=os.path.isfile):
    for dirname in sys.path:
        candidate = os.path.join(dirname, pathname)
        if matchFunc(candidate):
            return candidate
    raise Error("Can't find file %s" % pathname)
def findFile(pathname):
    return _find(pathname)
def findDir(path):
    return _find(path, matchFunc=os.path.isdir)

大的Python应用由Python代码文件和很多资源文件组成.将它们放在一起对以后的使用和发布都是极为便利的 ,使用本节的方法或者2.18节的方法都很容易能找到它们.

相关说明:

isdir(path)
    Test whether a path is a directory
isfile(path)
    Test whether a path is a regular file

Comments: 发表评论



<< Home

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