Search code examples
python-3.xpathpathlib

How do you combine more than one pathlib object?


I've got two Path objects using Python's pathlib library, pathA = Path('/source/parent') and pathB = Path('/child/grandchild'). What's the most direct way to combine the two so that you get a Path('/source/parent/child/grandchild') object?


Solution

  • According to the docs:

    You can do this easy by pathlib.PurePath(*pathsegments)

    "Each element of pathsegments can be either a string representing a path segment, an object implementing the os.PathLike interface which returns a string, or another path object."

    >>> PurePath('foo', 'some/path', 'bar')
    PurePosixPath('foo/some/path/bar')
    >>> PurePath(Path('foo'), Path('bar'))
    PurePosixPath('foo/bar')
    

    So for you it would be:

    pathA = pathlib.Path('source/parent')
    pathB = pathlib.Path('child/grandchild')
    pathAB = pathlib.PurePath(pathA, pathB)
    

    Output: source/parent/child/grandchild
    

    Note

    "When several absolute paths are given, the last is taken as an anchor (mimicking os.path.join()’s behaviour):"

    >>> PurePath('/etc', '/usr', 'lib64')
    PurePosixPath('/usr/lib64')
    >>> PureWindowsPath('c:/Windows', 'd:bar')
    PureWindowsPath('d:bar')
    

    Even when you do this:

    pathA = pathlib.Path('/source/parent')
    pathB = pathlib.Path('/child/grandchild')
    pathAB = pathlib.PurePath(pathA, pathB)
    

    Pathlib will handle pathB like a path object that is represented by a string.

    Output: source/child/grandchild