Differences between revisions 2 and 4 (spanning 2 versions)
Revision 2 as of 2004-09-26 00:32:13
Size: 4281
Editor: 61
Revision 4 as of 2004-09-26 00:52:41
Size: 4819
Editor: 61
Deletions are marked like this. Additions are marked like this.
Line 59: Line 59:
在不得不进行许多次路径处理之后,我设计了这个类.一般使用os.path.join就可以了,但是使用如下代码有点笨笨的感觉: 在不得不进行许多次路径处理之后,我设计了这个类.一般使用os.path.join就可以了,但是代码有点笨笨的感觉:
Line 77: Line 77:
译注,个人观点: 设计该从用户出发, 用户真的需要重载'''/'''符号吗? 这个牵强了些. 概念本来是'''加法 +''',现在变成了'''除法 /''', 用户理解这个转换不直观, 觉得不如os.path.join好,或者名称的改为append好些,或者重载符号'''+'''。 学python的都厉害(我除外), 也不好说了:> :) 译注,个人观点: 设计该从用户出发, 用户真的需要重载'''/'''符号吗? 这个牵强了些. 虽然是附加"/"和子路径,但是概念本来是'''加法 +''',现在变成了'''除法 /''', 用户理解这个转换不直观. 觉得不如os.path.join好,或者重载符号'''+'''。 学python的都厉害(我除外), 也不好说了 :)
Line 94: Line 94:

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

Line 101: Line 107:
Line 102: Line 109:

在_translate 字典中简单查询'''other''',如果没有,忽略处理。
Line 106: Line 116:
Recipe 4.16; documentation for the os.path module in the Library Reference. 食谱4.16; http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d4_2d16;


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

文章来自《Python cookbook》.


-- [DateTime(2004-09-26T00:32:13Z)] TableOfContents


Treating Pathnames as Objects


Credit: David Ascher

问题 Problem

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


解决 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)))
   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.


讨论 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:


   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
>>> print len(sitepkgs)
>>> 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' / "."

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;


#译注参考:食谱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)