How does abspath determine if a path is relative?
I know that abspath can take a file or a relative set of files and make the full path for them by adding the current directory as shown in these examples:
>>> 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'
And the full path provided will be considered absolute and will not add this path:
>>> 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'
My question is, how does abspath know how to do this? This is on Windows, so it checks for the "@:" at the beginning (where @ is any alphabet character)?
If so, how do other operating systems define it? The Mac path '/ Volumes /' is less clearly identifiable as a directory.
source to share
As for the implementation in CPython , the absolute path in Windows 95 and Windows NT is checked as follows:
# 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)
This function is called abspath
if _getfullpathname
not available. Unfortunately I couldn't find an implementation _getfullpathname
.
Implementation abspath
(if _getfullpathname
not available):
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)
source to share