Python: Find a shared path by components
os.path.commonpath() compares complete path components. commonprefix() compares characters, so its result can stop halfway through a directory name. Use the component comparison when grouping paths under a shared parent.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as path_components.py in an empty working directory:
from os.path import commonpath, commonprefix
paths = ["/srv/reports/run-a", "/srv/reports/run-b"]
print("Character prefix:", commonprefix(paths))
print("Path prefix:", commonpath(paths))
try:
commonpath(["/srv/reports", "reports/run-a"])
except ValueError:
print("Mixed absolute and relative paths: rejected")Run it without -O so any assertions remain enabled:
python3 path_components.pyCaptured output:
Character prefix: /srv/reports/run-
Path prefix: /srv/reports
Mixed absolute and relative paths: rejectedThe character prefix ends at run-, which is not a complete directory name in either input. The component result ends at reports. Mixing absolute and relative inputs raises ValueError; decide which form your application accepts before grouping them.
Limits and cleanup
These functions inspect strings without opening the named paths. commonpath() does not resolve symbolic links or prove that a file stays inside an allowed directory. Use it for lexical grouping, not as the sole security check for opening files.
After testing, remove the example script from its working directory:
rm -- path_components.pyReference
Acknowledgements
This post was created with assistance from AI.