abspath 如何确定路径是否为相对路径?
How does abspath determine if a path is relative?
我知道 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/”路径作为目录不太容易区分。
参考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)
我知道 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/”路径作为目录不太容易区分。
参考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)