os.path.abspath
abspath(p) is normpath(join(os.getcwd(), p)) — the result depends on the folder you run from, and the file does not have to exist. realpath asks the file system and follows symlinks, so it gives the true location; with strict=True (3.10+) it raises if a component is missing.
Demo
import posixpath cwd = '/home/ada/project' # stands in for os.getcwd() posixpath.abspath(posixpath.join(cwd, 'data/raw.csv'))
A relative path is glued onto the current directory and normalized: '../shared/./lib' from /home/ada/project is /home/ada/shared/lib. An absolute path ignores the current directory (join discards it) and is only normalized. On your machine os.path.abspath uses your real current directory — and on Windows ntpath.abspath asks Windows for the full path, drive letter included.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| path | str | bytes | PathLike | yes | Relative paths are resolved against os.getcwd(). |
| strict | bool | no (False) | realpath only (3.10+): True raises OSError when a path component does not exist or a symlink loop is found. |
Return value
str | bytes — An absolute, normalized path. realpath additionally has no symlinks in it.
Common patterns
import os BASE = os.path.dirname(os.path.abspath(__file__)) templates = os.path.join(BASE, 'templates')
import os key = os.path.normcase(os.path.realpath(path))
import os resolved = os.path.realpath(path, strict=True)
Examples
Pitfalls
import os, contextlib os.mkdir('elsewhere') with contextlib.chdir('elsewhere'): p = os.path.abspath('config.toml') os.path.basename(os.path.dirname(p))
import os, contextlib os.mkdir('elsewhere') base = os.path.abspath('.') with contextlib.chdir('elsewhere'): p = os.path.join(base, 'config.toml') os.path.dirname(p) == base
import os os.path.isabs(os.path.abspath('typo.txt'))
import os try: os.path.realpath('typo.txt', strict=True) found = True except FileNotFoundError: found = False found
When to use
- Turning user input or __file__ into a full path (abspath)
- Finding the real location behind symlinks (realpath)
- pathlib code → Path.absolute() / Path.resolve()
- Just cleaning text → normpath
Notes
FAQ
os.path.abspath(path), or Path(path).resolve() with pathlib (which also follows symlinks, like realpath).