8

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

1
  • as per my knowledge, you can use either interchangeably. Commented Jun 30, 2022 at 20:44

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

There is actually a small difference. Using slashes Python instantiates the Path object for every intermediary path while joinpath produces the final path in one go, making it significantly faster for joining long paths. It doesn't usually matter unless you are building millions of long paths and you want to save a microsecond or two on each.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.