Python Glossary Русский

all Python 3osfunction

os.path.expanduser

os.path — making paths absolute

Expand a leading `~` (or `~user`) to the user's home directory.

Syntax

os.path.expanduser(path)

It expands a tilde only at the start of a path: 'a~b' is left alone. If ~name names no existing user, the path comes back unchanged and without an error — check the result. On Unix the home directory comes from HOME, on Windows from USERPROFILE. The interpreter itself never expands tildes: open('~/x') looks for a directory literally named '~'.

Examples

import os
print(os.path.expanduser('foo'))   # → foo
print(os.path.expanduser('~'))   # → домашний каталог пользователя, например /home/user
cfg = os.path.expanduser('~/.config/app.json')
print(os.path.isabs(cfg))   # → True (типовой приём: путь к конфигу в домашнем каталоге вместо жёсткого /home/...)
print(os.path.expanduser('/tmp/~/x'))   # → /tmp/~/x (раскрывается только ведущий '~', внутри пути он остаётся символом)
print(os.path.expanduser('~несуществующий/x'))   # → только Unix: '~несуществующий/x' без изменений — такого пользователя нет, исключение не бросается

See also

Open in the full glossarydocs.python.orgReport an inaccuracy