A word of caution on os.path.abspath

Sep 23, 2014

Due to the implementations of abspath in Python, it requires some careful consideration. The source code for os.path.abspath can be found in the posixpath.py file in your Python installation folder. Windows users open ntpath.py instead. Have a look at the abspath function (I'm quoting what I saw in posixpath.py) :

def abspath(path):
    """Return an absolute path."""
    if not isabs(path):
        if isinstance(path, _unicode):
            cwd = os.getcwdu()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)

This function determines the absolute path by joining the path of the Current Working Directory(CWD) with the value in path argument. It is the responsibility of the user/coder to make sure that the path argument contains an address relative to the CWD.

One example where this can cause a hard to identify bug is if you try to resolve the absolute path of a file after changing your CWD using the os.chdir function. I once "lost" a config file despite it sitting right there.