The os
module in the standard library includes the path
submodule which offers convenient functions for working with and manipulating paths.
The abspath()
function in the path
module is used to get the absolute path from a relative path. Absolutes path refers to the full, explicit path from the root of a file system to a particular file or directory while a relative path refers to a path relative to the present working directory.
Calling the abspath()
from a particular directory will append the current directory's absolute path to the given file or directory. The function does not validate whether the given or the resulting path actually exists.
To use the abspath()
function, we first need to import it from the path module as shown below.
from os.path import abspath
abspath(p)
p |
The relative path. |
#on windows from desktop folder
from os.path import abspath
relp = "images/john.png"
absp = abspath(rel)
print(absp)
C:\Users\John\Desktop\images\john.png
In the above example, calling the abspath()
from desktop folder on a Windows leads to the the absolute path to desktop being appended at the beginning of the input path, similarly, if you call the interpreter from another directory,
from os.path import abspath
relp = 'project/tests'
absp = abspath(rel)
print(absp)
C:\Users\John\Desktop\myprojects\project/tests
As earlier mentioned, the abspath()
function works on mere strings, it doesn't matter whether the string is a valid path or not, it simply appends the absolute path to the current files directory at the beginning of the input string.