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

Contents

1. 描述

# 描述

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:

```   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.

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

```>>> 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.).

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:

```>>> 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.

python文档os.path模块部分

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

• Page.execute = 0.790s
• getACL = 0.115s
• init = 0.005s