Get Absolute Path in Python

Get Absolute Path in Python

Rayven Esplanada Mar-04, 2021 Feb-10, 2021 Python Python Path
  1. Use abspath() to Get the Absolute Path in Python
  2. Use the Module pathlib to Get the Absolute Path in Python

This tutorial will demonstrate how to get the absolute path of a file or a folder in Python.

Use abspath() to Get the Absolute Path in Python

Under the Python module os are useful utility functions and properties that manipulate and access file paths under the os.path property. To get the absolute path using this module, call path.abspath() with the given path to get the absolute path.

import os

simp_path = 'demo/which_path.docx'
abs_path = os.path.abspath(simp_path)

print(abs_path)

The output of the abspath() function will return a string value of the absolute path relative to the current working directory.

Output:

/Users/user/python/demo/which_path.docx

Use the Module pathlib to Get the Absolute Path in Python

The Python module pathlib offers similar functions as os.path and contains classes representing file paths with their corresponding properties and functions used for path manipulation and access.

To get the absolute path using pathlib, import the Path class from the pathlib module and use the Path.absolute() function of that class to determine the absolute path of a given file or folder.

from pathlib import Path

fpath = Path('sample2.py').absolute()

print(fpath)

Setting the absolute path as a parameter is also supported and will print it straightforwardly instead of appending the root folders and making it redundant.

from pathlib import Path

fpath = Path('/Users/user/python/sample2.py').absolute()

print(fpath)

Both instances will produce the same output:

/Users/user/python/sample2.py

In summary, there are two easy ways to get the absolute path of a file or a folder in Python under the modules os and pathlib. Performance-wise, both solutions are relatively fast, and it’s only a matter of preference as to which solution the developer wants to use.

Related Article - Python Path

  • Solve Configure: Error: No Acceptable C Compiler Found in $PATH
  • The Path Python3 (From --Python=Python3) Does Not Exist
  • Get Directory From Path in Python
  • Set File Path in Python
  • Change Python Path
  • Relative Path in Python