文章来自《Python cookbook》.

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

-- 61.182.251.99 [2004-09-26 00:32:13]

描述

Treating Pathnames as Objects

将路径作为对象处理

Credit: David Ascher

问题 Problem

You want to manipulate path objects as if they were sequences of path parts.

需要处理路径对象使它可以作为由路径各部分组成的list序列使用

解决 Solution

Although it is only available this elegantly in Python 2.2 and later, you can create a subclass of the string type that knows about pathnames:

虽然在Python 2.2及以后版本中可以优雅的实现,但是可以继承String类处理路径,使得它可以作为序列使用:

   1 _translate = { '..': os.pardir }
   2 class path(str):
   3    def _ _str_ _(self):
   4        return os.path.normpath(self)                 #返回规范化的路径字符串
   5    def _ _div_ _(self, other):                       #用"/"间隔,附加一部分?
   6        other = _translate.get(other, other)
   7        return path(os.path.join(str(self), str(other)))
   8 
   9    def _ _len_ _(self):                               #返回路经组成部分的数目 
  10        return len(splitall(str(self)))
  11    def _ _getslice_ _(self, start, stop):            #获得分片 
  12        parts = splitall(str(self))[start:stop]
  13        return path(os.path.join(*parts))
  14    def _ _getitem_ _(self, i):                       #返回一部分
  15        return path(splitall(str(self))[i])

Note that this solution relies on Recipe 4.16.

这里的实现依赖于食谱4.16.     

讨论 Discussion

I designed this class after I had to do a lot of path manipulations. These are typically done with a function such as os.path.join, which does the job well enough, but is somewhat cumbersome to use:

在不得不进行许多次路径处理之后,我设计了这个类.一般使用os.path.join就可以了,但是代码有点笨笨的感觉:

   1 root = sys.prefix
   2 sitepkgs = os.path.join(root, 'lib', 'python', 'site-packages')

To use this recipe, the first path must be created with the path function. After that, divisions are all that we need to append to the path: 利用本食谱方法的需要先使用path构造函数,然后用重载"/"操作符来附加各部分

root = path(sys.prefix)
sitepkgs = root / 'lib' / 'python' / 'site-packages'

As an additional bonus, you can treat the path as a sequence of path parts:

作为额外的奖励,可以将路径作为(由"/","\" 或"::"分割的)序列使用:

译注,个人观点: 设计该从用户出发, 用户真的需要重载/符号吗? 这个牵强了些. 虽然是附加"/"和子路径,但是概念本来是加法 +,现在变成了除法 /, 用户理解这个转换不直观. 觉得不如os.path.join好,或者重载符号+。 学python的都厉害(我除外), 也不好说了 :)

>>> print sitepkgs
C:\Apps\Python22\lib\python\site-packages
>>> print len(sitepkgs)
6
>>> sitepkgs[0], sitepkgs[1], sitepkgs[-1]
('C:\\', 'Apps', 'site-packages')

This class could be made richer by, for example, adding method wrappers for many of the functions that are defined in the os.path module (isdir, exists, etc.).

可以扩展这个类, 使其功能丰富, 比如 : 对于os.path模块中大量函数(isdir,exists等),提供函数wrapper.

The code is fairly straightforward, thanks to the ease with which one can subclass strings in Python 2.2 and later. The call to os.path.normpath is important, since it ensures that casual use of . and .. do not wreak havoc:

上面方法中从Python2.2 string类的继承很容易, 代码意思很直观. 使用os.path.normpath很重要, 保证偶尔出现的 "." 或者 ".." 不会造成灾难

>>> root / '..' / 'foo' / "."
'C:\\Apps\\foo\\.'

The overriding of the division operator uses a little trick that is overkill for this recipe but can come in handy in other contexts. The following line:

重载"/"符号使用了一点小技巧,对于本节的处理,显得过于大材小用些,但在许多情况下,都可以使用的.

如下代码:

other = _translate.get(other, other)

does a simple lookup for other in the _translate dictionary and leaves it alone if that key isn't found in the dictionary.

在_translate 字典中简单查询other,如果没有,忽略处理。

参考 See Also

食谱4.16; http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d4_2d16;

python文档os.path模块部分

#译注参考:食谱1.4 http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d1_2d4

PyCkBk-4-17 (last edited 2009-12-25 07:09:08 by localhost)