0
0
PythonHow-ToBeginner · 3 min read

How to Get Relative Path in Python: Simple Guide

In Python, you can get the relative path between two locations using pathlib.Path.relative_to() or os.path.relpath(). These methods return the path from one directory to another as a relative path string.
📐

Syntax

There are two common ways to get a relative path in Python:

  • Using pathlib: Path.relative_to(other_path) returns the relative path from other_path to the current path.
  • Using os.path: os.path.relpath(path, start) returns a relative path from start to path. If start is omitted, it defaults to the current working directory.
python
from pathlib import Path
import os

# Using pathlib
relative_path = Path('/home/user/docs/file.txt').relative_to('/home/user')

# Using os.path
relative_path_os = os.path.relpath('/home/user/docs/file.txt', '/home/user')
💻

Example

This example shows how to get the relative path from one folder to a file using both pathlib and os.path. It prints the relative path as a string.

python
from pathlib import Path
import os

file_path = Path('/home/user/docs/file.txt')
start_path = Path('/home/user')

# Using pathlib
try:
    relative_path = file_path.relative_to(start_path)
    print(f"Relative path using pathlib: {relative_path}")
except ValueError:
    print("pathlib: The start path is not a parent of the file path.")

# Using os.path
relative_path_os = os.path.relpath(str(file_path), str(start_path))
print(f"Relative path using os.path: {relative_path_os}")
Output
Relative path using pathlib: docs/file.txt Relative path using os.path: docs/file.txt
⚠️

Common Pitfalls

1. pathlib.Path.relative_to() requires the start path to be a parent of the target path. If it is not, it raises a ValueError. This means you cannot get a relative path if the start is not above the target in the folder tree.

2. os.path.relpath() works even if the start path is not a parent, by calculating the relative path with .. to go up directories.

3. Always convert paths to strings when using os.path functions if you use pathlib.Path objects.

python
from pathlib import Path

file_path = Path('/home/user/docs/file.txt')
start_path = Path('/home/other')

# This will raise ValueError because start_path is not a parent
try:
    print(file_path.relative_to(start_path))
except ValueError as e:
    print(f"Error: {e}")

# os.path.relpath works fine
import os
print(os.path.relpath(str(file_path), str(start_path)))
Output
Error: '/home/user/docs/file.txt' does not start with '/home/other' ../user/docs/file.txt
📊

Quick Reference

Use this quick guide to choose the right method:

MethodUse WhenNotes
pathlib.Path.relative_to()Start path is a parent of target pathRaises error if not parent
os.path.relpath()Any two pathsReturns relative path with .. if needed
MethodUse WhenNotes
pathlib.Path.relative_to()Start path is a parent of target pathRaises error if not parent
os.path.relpath()Any two pathsReturns relative path with .. if needed

Key Takeaways

Use pathlib.Path.relative_to() when the start path is a parent directory of the target path.
Use os.path.relpath() to get relative paths between any two paths, even if unrelated.
pathlib raises ValueError if the start path is not a parent; os.path.relpath handles this gracefully.
Convert pathlib.Path objects to strings when using os.path functions.
Relative paths help make file references flexible and portable across systems.