Python Glossary Русский

Python 3.4+pathlibterm

/ operator

union

The / operator on Path objects joins the components of a path, like os.path.join().

Syntax

Path('dir') / 'subdir' / 'file.txt'

Joining is pure string work — nothing is created or checked on disk, and '..' is not collapsed, so Path('a/b') / '..' stays 'a/b/..' until you call resolve(). An absolute right-hand component discards everything on the left: Path('/home/user') / '/etc' is just '/etc', which bites when the right side comes from user input. Only one side has to be a Path; the other may be a plain string.

Examples

from pathlib import Path
base = Path('/home/user')
p = base / 'docs' / 'report.txt'
str(p) # → '/home/user/docs/report.txt'
Path('/etc') / 'nginx' / 'nginx.conf'  # → PosixPath('/etc/nginx/nginx.conf')
from pathlib import Path
Path('src') / Path('main.py') # → PosixPath('src/main.py')

See also

Open in the full glossarydocs.python.orgReport an inaccuracy