all Python 3osfunction
os.path.relpath
os.path — path parsing
Return a path to `path` relative to the `start` directory.
Syntax
os.path.relpath(path, start=os.curdir)
It computes the path from strings without touching the disk, so it works for paths that do not exist but ignores symlinks. By default start is the current directory, so the result depends on where the program was launched from. On Windows paths on different drives raise ValueError: there is no relative path between C: and D:.
Examples
import os
print(os.path.relpath('/a/b/c', '/a/b')) # → c
print(os.path.relpath('/a/b', '/a/b')) # → .
print(os.path.relpath('/a', '/a/b')) # → .. — если цель выше start, путь строится через переходы вверх
print(os.path.relpath('/нет-такого/файл.txt', '/нет-такого')) # → файл.txt — файлы могут не существовать, relpath работает с текстом пути
print(os.path.relpath('/a/b/c')) # → путь к /a/b/c от текущего каталога (start по умолчанию — os.curdir), например ../../a/b/c
See also
Open in the full glossarydocs.python.orgReport an inaccuracy