Search code examples
python-3.xpathlib

Difference between "joinpath" and "/" in Pathlib


Is there a difference between joinpath and the / operator in the pathlib module? The documentation doesn't ever compare the two methods. Essentially are there any cases where these two are different?

Example:


from pathlib import Path

foo = Path("some_path")
foo_bar_operator = foo / "bar"
foo_bar_joinpath = foo.joinpath("bar")

foo_bar_operator == foo_bar_joinpath
# Returns: True


Solution

  • There is no difference. The source code confirms this:

        def joinpath(self, *args):
            """Combine this path with one or several arguments, and return a
            new path representing either a subpath (if all arguments are relative
            paths) or a totally different path (if one of the arguments is
            anchored).
            """
            return self._make_child(args)
    
        def __truediv__(self, key):
            try:
                return self._make_child((key,))
            except TypeError:
                return NotImplemented
    

    Note you can pass multiple arguments to joinpath e.g. a.joinpath(b, c, d). The equivalent for / would be a / b / c / d.