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.
Python code
18 linesfrom 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
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
- Use `os.path.realpath(path_string)` for the equivalent with the stdlib `os` module
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.