Python os.path.relpath
Compute a relative path between locations sharing a base.
A simple example
os.path.relpath
- Start with Start at notes, target notes/a.txt
- Do this Find the relative route
- Result a.txt
Syntax
os.path.relpath(image, start=notes)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyLink a course handout to a diagram
A course will move between the teacher’s laptop and the school server. Compute a relative route from its notes folder to a sibling image folder so the handout can still find the same diagram.
from pathlib import Path
from tempfile import TemporaryDirectory
import os
with TemporaryDirectory() as folder:
base = Path(folder)
image = base / "images" / "map.png"
print(Path(os.path.relpath(image, start=base / "notes")).as_posix())
../images/map.png
Go up one directory from notes, then enter images and select the diagram.
Locate a rehearsal score
The choir stores each score inside a season folder. A catalogue starts in the parent directory. Which relative link reaches the file in the named subfolder? Use forward slashes in this example.
Locate a workshop handout
An instructor stores the current template in a class folder. A catalogue starts in the parent directory. Which relative link reaches the file in the named subfolder? Use forward slashes in this example.
What to watch for
Both paths need compatible roots. The result depends on which directory is the starting point.