PythonCookbook-2.20在Python的搜索路径中寻找文件
- 游戏开发
- 2025-09-21 07:42:02

任务
一个大的 Python 应用程序包括了资源文件(比如 Glade 项目文件、SQL 模板和图片)以及 Python 包(Python package)。你想把所有这些相关文件和用到它们的 Python 包储存起来。
解决方案可以在 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 files" %pathname) def findFile(pathname): return _find(pathname) def findDir(path): return _find(path, matchFunc = os.path.isdir) 讨论比较大的 Python 应用程序由一系列 Python 包和相关的资源文件组成。将这些相关文件和用到它们的 Python 包一起储存起来是很方便的,可以很容易地对 2.18 提供的代码略加修改,使之能根据 Python 搜索路径的相对路径来寻找文件和目录。
PythonCookbook-2.20在Python的搜索路径中寻找文件由讯客互联游戏开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“PythonCookbook-2.20在Python的搜索路径中寻找文件”