How to resolve a symlink to its real path in Python with pathlib

Use Path.resolve() to turn a symlink path into its absolute target path, handling relative symlinks and eliminating symbolic links.

Easy Python 3.9+ Aug 9, 2026 Files & data 14 views 0 copies

Python code

18 lines
Python 3.9+
from pathlib import Path

def resolve_symlink(path):
    p = Path(path)
    return str(p.resolve())

if __name__ == "__main__":
    # Create a symlink to demonstrate the resolution
    target = Path("/tmp/real_target.txt")
    target.write_text("hello")
    link = Path("/tmp/my_link.txt")
    try:
        link.symlink_to(target)
        print(f"Symlink path: {link}")
        print(f"Real path:   {resolve_symlink(link)}")
    finally:
        target.unlink()
        link.unlink()

Output

stdout
Symlink path: /tmp/my_link.txt
Real path:   /tmp/real_target.txt

How it works

Path.resolve() returns the absolute path with all symbolic links expanded to their targets. It uses os.path.realpath under the hood, which resolves symlinks and normalizes the path. The method also resolves relative paths against the current working directory and handles .. segments. This is useful when you need the canonical filesystem location for operations that don't follow symlinks, like file comparison or storing file paths in a database.

Common mistakes

  • Using `Path.absolute()` instead of `resolve()` — `absolute()` doesn't expand symlinks
  • Forgetting that `resolve()` can raise `OSError` if the path doesn't exist, unless `strict=False` is passed
  • Assuming `resolve()` works on broken symlinks — by default it raises an error, use `strict=False` for that case

Variations

  1. Use `os.path.realpath(path_string)` for the equivalent with the stdlib `os` module
  2. Call `p.resolve(strict=False)` to return a normalized absolute path even if the symlink target does not exist

Real-world use cases

  • Normalizing uploaded file paths in a web app so stored paths never contain symlinks or relative segments.
  • Deduplicating files by their real inode path in a backup or sync tool to avoid processing the same file twice.
  • Building a search index that maps symlinks to their canonical target for consistent document identity.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.