Python recipe(13):路径操作

代码何在?

div css xhtml xml Example Source Code Example Source Code [http://www.cnblogs.com/tomsheep/]
'''
Created on 2010-5-25

@author: lk
'''
import os,operator

def splitall(path):
    allparts = []
    while 1:
        parts = os.path.split(path)
        if parts[0]== path: #absolute path
            allparts.insert(0, path)
            break
        elif parts[1] == path: #relative path
            allparts.insert(0, path)
            break
        else:
            path = parts[0]
            allparts.insert(0, parts[1])
    return allparts

_translate={'..':os.pardir}
class path(str):
    def __str__(self):
#        print '__str__'
        return os.path.normpath(self)
    def __div__(self,other):
        '''concatenate pathname'''
#        print '__div__'
        other = _translate.get(other,other)
        return path(os.path.join(str(self), str(other)))
    def __len__(self):
        return len(splitall(str(self)))
    def __getslice__(self,start,stop):
        parts = splitall(str(self))[start:stop]
        return path(os.path.join(*parts))
    def __getitem__(self,i):
        return splitall(str(self))[i]
    
if __name__ == '__main__':
    path1 = r"C:\Windows\System32"
    path2 = r"System32"
    path3 = r"Windows\System32"
    print os.path.split(path1)
    print os.path.split(path2)
    print os.path.split(path3)
    print os.path.normpath(path1)
    print os.path.normpath(path2)
    print os.path.normpath(path3)
    print os.path.join(path1,path2)
    print splitall(path1)  
    
    print _translate
    my_path1=path(path1)
    print str(my_path1)
    print my_path1/path2
    print len(my_path1)
    print operator.getslice(my_path1,1,2)
    print operator.getitem(my_path1,1)
    print my_path1.__getitem__(1)

以上代码改写自Python Cookbook 4-16 4-17

概述:

    自定义path类对目录进行包装,重载了许多方便有用的运算符

代码说明:

1. os.path.split函数将路径分为两部分,(head,tail) ,tail是路径中最后一部分,如果path本身是绝对根目录,则tail为空,若path本身是相对路径且只有一项,head为空

2.os.path.join 接受变长参数,连接这些路径;os.path.normal返回路径的“规范格式”

3.字典的get(key,other)函数首先查找key,找到则返回对应值,没有则返回other

4.自定义path继承了标准库的str,并且重载了许多操作符,比如__div__即支持“除”操作。关于操作符重载我是这样认为的(我没有查书,可能不对):注意到这些操作符都在operator库中有定义,而且operator.op(obj, args)等同于obj.__op__(args),这应该是一种“契约”,调用时通过查找是否有匹配的函数名来进行操作。并且为了方便,operator中的许多操作符都被默认import到了程序空间中(?),比如len,str,以及便捷中缀简写’/’’+’等也应属此类。

posted on 2010-05-25 18:11  tomsheep  阅读(353)  评论(0编辑  收藏  举报

导航