Python Glossary Русский

Python 3.5+osfunction

os.path.commonpath

os.path — path parsing

Return the longest common sub-path of a list — component-wise.

Syntax

os.path.commonpath(paths)

It suits the "is this path inside that directory" check: commonpath([base, target]) == base, provided both paths went through realpath first. Mixing absolute and relative paths raises ValueError, as does an empty list. On Windows paths on different drives raise ValueError too.

Examples

import os
print(os.path.commonpath(['/usr/a', '/usr/b']).endswith('usr'))   # → True
print(os.path.commonpath(['a/b/c', 'a/b/d']) == os.path.join('a', 'b'))   # → True
files = ['/var/log/app/a.log', '/var/log/app/b.log', '/var/log/db/c.log']
print(os.path.commonpath(files).endswith(os.path.join('var', 'log')))   # → True
print(os.path.commonprefix(['/usr/lib', '/usr/local']))   # → /usr/l — посимвольно; с 3.15 commonprefix даёт DeprecationWarning
print(os.path.commonpath(['/usr', 'usr']))   # → ValueError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy