0
0
PythonHow-ToBeginner · 3 min read

How to Get Absolute Path in Python: Simple Guide

In Python, you can get the absolute path of a file or directory using os.path.abspath(path) or pathlib.Path(path).resolve(). These methods convert a relative path to a full path starting from the root of your file system.
📐

Syntax

The two common ways to get an absolute path in Python are:

  • os.path.abspath(path): Takes a string path and returns its absolute path as a string.
  • pathlib.Path(path).resolve(): Creates a Path object and returns its absolute path as a Path object.
python
import os
from pathlib import Path

absolute_path_os = os.path.abspath('relative/path/to/file')
absolute_path_pathlib = Path('relative/path/to/file').resolve()
💻

Example

This example shows how to get the absolute path of a file named example.txt located in a relative folder docs. It prints the absolute paths using both os.path and pathlib.

python
import os
from pathlib import Path

relative_path = 'docs/example.txt'

absolute_path_os = os.path.abspath(relative_path)
absolute_path_pathlib = Path(relative_path).resolve()

print('Absolute path using os.path:', absolute_path_os)
print('Absolute path using pathlib:', absolute_path_pathlib)
Output
Absolute path using os.path: /home/user/project/docs/example.txt Absolute path using pathlib: /home/user/project/docs/example.txt
⚠️

Common Pitfalls

Common mistakes when getting absolute paths include:

  • Using os.path.abspath() on a path that does not exist still returns an absolute path, which might be misleading.
  • Not handling symbolic links: os.path.abspath() does not resolve symlinks, but pathlib.Path.resolve() does by default.
  • Confusing relative paths with absolute paths, especially when running scripts from different working directories.
python
import os
from pathlib import Path

# Wrong: expecting abspath to resolve symlinks
print(os.path.abspath('some_symlink'))  # May not resolve symlink

# Right: pathlib resolves symlinks
print(Path('some_symlink').resolve())
📊

Quick Reference

MethodDescriptionReturns
os.path.abspath(path)Returns absolute path as stringstring
pathlib.Path(path).resolve()Returns absolute path resolving symlinksPath object
os.getcwd()Returns current working directorystring

Key Takeaways

Use os.path.abspath() to get absolute path as a string from a relative path.
Use pathlib.Path(path).resolve() to get an absolute Path object and resolve symlinks.
Absolute paths start from the root directory and are independent of the current working directory.
os.path.abspath() does not resolve symbolic links, but pathlib.Path.resolve() does.
Always check your current working directory when working with relative paths.