Fix Python – How to get absolute path of a pathlib.Path object?


Asked By – EquipDev

Making a path object with pathlib module like:

p = pathlib.Path('file.txt')

The p object will point to some file in the filesystem, since I can do for example p.read_text().

How can I get the absolute path of the p object in a string?

Appears that I can use for example os.path.abspath(p) to get the absolute path, but it awkward to use an os.path method, since I assume that pathlib should be a replacement for os.path.

Now we will see solution for issue: How to get absolute path of a pathlib.Path object?


You’re looking for the method .absolute, if my understanding is correct, whose documentation states:

>>> print(p.absolute.__doc__)
Return an absolute version of this path.  This function works
        even if the path doesn't point to anything.

        No normalization is done, i.e. all '.' and '..' will be kept along.
        Use resolve() to get the canonical path to a file.

With a test file on my system this returns:

>>> p = pathlib.Path('testfile')
>>> p.absolute()

This method seems to be a new, and still, undocumented addition to Path and Path inheritting objects.

Created an issue to document this.

This question is answered By – Dimitris Fasarakis Hilliard

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0