Size: 1719
Comment:
|
Size: 2298
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 22: | Line 22: |
大规模的Python应用程序包括资源文件(比如Glade?项目文件,SQL模板,图像文件等)和Python包。 | 大规模的Python应用程序包括资源文件(比如Glade?项目文件,SQL模板,图像文件等)和Python包。 需要将资源文件和使用它们的Python包存放在一起。 |
Line 26: | Line 26: |
需要相对于Python的sys.path, 查找文件或目录: {{{ #!python |
|
Line 44: | Line 49: |
}}} |
|
Line 48: | Line 55: |
比较大的Python应用程序包含很多Python包一级关联的资源文件。将资源文件同相关的Python包存放在一起,使用起来很方便 。对于这样的文件存储方式, 将食谱4.21方法加以变化,在相对于Python搜索路径的相对目录中查找文件或目录,简单一些。 | |
Line 52: | Line 59: |
食谱 4.21 http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d4_2d21 Python文档 os模块部分 |
文章来自《Python cookbook》. 翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!
-- 218.25.66.198 [DateTime(2004-09-29T04:52:50Z)] TableOfContents
描述
- Finding a File on the Python Search Path
在Python搜索路径上查找文件
Credit: Mitch Chapman
问题 Problem
A large Python application includes resource files (e.g., Glade project files, SQL templates, and images) as well as Python packages. You want to store these associated files together with the Python packages that use them.
大规模的Python应用程序包括资源文件(比如Glade?项目文件,SQL模板,图像文件等)和Python包。 需要将资源文件和使用它们的Python包存放在一起。
解决 Solution
You need to be able to look for either files or directories along Python's sys.path:
需要相对于Python的sys.path, 查找文件或目录:
1 import sys, os
2
3 class Error(Exception): pass
4
5 def _find(pathname, matchFunc=os.path.isfile):
6 for dirname in sys.path:
7 candidate = os.path.join(dirname, pathname)
8 if matchFunc(candidate):
9 return candidate
10 raise Error("Can't find file %s" % pathname)
11
12 def findFile(pathname):
13 return _find(pathname)
14
15 def findDir(path):
16 return _find(path, matchFunc=os.path.isdir)
讨论 Discussion
Larger Python applications consist of sets of Python packages and associated sets of resource files. It's convenient to store these associated files together with the Python packages that use them, and it's easy to do so if you use this variation on Recipe 4.21 to find files or directories with pathnames relative to the Python search path.
比较大的Python应用程序包含很多Python包一级关联的资源文件。将资源文件同相关的Python包存放在一起,使用起来很方便 。对于这样的文件存储方式, 将食谱4.21方法加以变化,在相对于Python搜索路径的相对目录中查找文件或目录,简单一些。
参考 See Also
Recipe 4.21; documentation for the os module in the Library Reference
食谱 4.21 http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d4_2d21
Python文档 os模块部分