How to Get an Absolute File Path in Python

Created
Modified

Using abspath Function

The os.path.abspath() method returns a normalized absolutized version of the pathname path. For example,

#!/usr/bin/python3

# Import module
import os

abs = os.path.abspath("file.txt")
print(abs)
/home/python/code/file.txt

On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).

Using pathlib Module

The Path.resolve() method makes the path absolute, resolving any symlinks. A new path object is returned:

#!/usr/bin/python3

# Import module
import pathlib

abs = pathlib.Path("file.txt").resolve()
print(abs)
/home/python/code/file.txt

Related Tags