abspath如何确定路径是否相对?

时间:2015-04-28 10:15:44

标签: python operating-system

我知道abspath可以接受一个文件或一组相对文件,并通过在当前目录前添加一个完整的路径,如下例所示:

>>> os.path.abspath('toaster.txt.')
'C:\\Python27\\Lib\\idlelib\\toaster.txt'

>>> os.path.abspath('i\\am\\a\\toaster.txt.')
'C:\\Python27\\Lib\\idlelib\\i\\am\\a\\toaster.txt'

提供的完整路径将被识别为绝对路径,而不是在此路径前面:

>>> os.path.abspath('C:\\i\\am\\a\\toaster.txt.')
'C:\\i\\am\\a\\toaster.txt'
>>> os.path.abspath('Y:\\i\\am\\a\\toaster.txt.')
'Y:\\i\\am\\a\\toaster.txt'

我的问题是abspath如何知道这样做?这是在Windows上,所以它在开始时检查'@:'(其中@是任何字母字符)?

如果是这种情况,其他操作系统如何确定它? Mac的'/ Volumes /'路径与目录的区别不太明显。

1 个答案:

答案 0 :(得分:1)

参考implementation in CPython,正在检查Windows 95和Windows NT上的绝对路径:

# Return whether a path is absolute. 
# Trivial in Posix, harder on Windows. 
# For Windows it is absolute if it starts with a slash or backslash (current 
# volume), or if a pathname after the volume-letter-and-colon or UNC-resource 
# starts with a slash or backslash. 


def isabs(s): 
    """Test whether a path is absolute""" 
    s = splitdrive(s)[1]
    return len(s) > 0 and s[0] in _get_bothseps(s) 

如果abspath不可用,则_getfullpathname会调用此函数。不幸的是,我无法找到_getfullpathname的实现。

abspath的实施(如果_getfullpathname不可用):

def abspath(path): 
    """Return the absolute version of a path.""" 
    if not isabs(path): 
        if isinstance(path, bytes): 
            cwd = os.getcwdb() 
        else: 
            cwd = os.getcwd() 
        path = join(cwd, path) 
    return normpath(path)