all Python 3osfunction
os.path.realpath
os.path — making paths absolute
Return the canonical path, resolving any symlinks.
Syntax
os.path.realpath(path)
For a path that does not exist there is no error: the function resolves what it can and appends the rest unchanged. Pass strict=True (Python 3.10+) to get FileNotFoundError instead. It is the right first step before an "is this file inside the allowed directory" check: realpath first, then commonpath — otherwise an escape through a symlink goes unnoticed.
Examples
# Python 3.9+
import os
print(os.path.isabs(os.path.realpath('.'))) # → True
lib = os.path.dirname(os.__file__)
print(os.path.realpath(os.path.join(lib, 'json', '..', 'os.py')) == os.path.realpath(os.__file__)) # → True (лишние шаги и '..' схлопываются)
print(os.path.abspath('.') == os.path.realpath('.')) # → True (в обычном каталоге; False, если путь ведёт через символическую ссылку — abspath ссылки не разрешает)
try:
os.path.realpath('нет-такого-файла', strict=True)
except FileNotFoundError as e:
print(type(e).__name__) # → FileNotFoundError (при strict=True путь обязан существовать)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy