Python Glossary Русский

all Python 3osfunction

os.path.join()

os.path

Joins the components of a path the way the OS expects. An absolute component discards everything before it.

Syntax

os.path.join(path, *paths) -> str

An absolute component discards everything before it: join('data', '/etc/passwd') returns '/etc/passwd'. That makes joining a base directory with a user-supplied name dangerous — verify the result with realpath and commonpath. An empty last component adds a separator: join('a', '') gives 'a/'. For new code pathlib.Path with / is handier, but it treats an absolute component the same way.

Examples

import os
print(os.path.join('home', 'user', 'file.txt'))  # → home/user/file.txt
print(os.path.join('/etc', 'nginx', 'conf'))  # → /etc/nginx/conf
base = '/var/log'
print(os.path.join(base, 'app.log'))  # → /var/log/app.log
print(os.path.join('a/b', '../c'))  # → a/b/../c
print(os.path.join('a', '/abs'))  # → /abs  (абсолютный сбрасывает)

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy