【问题标题】:How does abspath determine if a path is relative?abspath 如何确定路径是否是相对的?
【发布时间】:2015-07-07 03:15:45
【问题描述】:

我知道 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/”路径作为目录不太容易区分。

【问题讨论】:

    标签: python operating-system


    【解决方案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) 
    

    如果_getfullpathname 不可用,此函数由abspath 调用。不幸的是,我找不到_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) 
    

    【讨论】:

    • 这是一个非常有帮助的答案!但是我对您引用的页面的一部分感到困惑,它说 对于 Windows,如果它以斜杠或反斜杠(当前卷)开头,则它是绝对的这不是相对路径而不是绝对路径?
    • 我刚刚在我的 Windows PC 上检查了它,实际上\foo 也指的是 Windows 中的绝对路径。准确地说,当前卷上的绝对路径 - 如突出显示的字符串所述。使用命令行自己尝试一下,转到C: 上的某个子文件夹,然后转到cd \Windows。它会再次将您带到C:\Windows
    • 啊哈,现在这对我来说很有意义。谢谢!
    猜你喜欢
    • 2014-06-27
    • 1970-01-01
    • 2012-07-09
    • 2014-03-09
    • 2011-10-16
    • 2020-11-07
    • 1970-01-01
    • 2010-10-25
    • 2020-02-28
    相关资源
    最近更新 更多