Is there a Pathlib alternate for os.path.join?

Each Answer to this Q is separated by one/two green lines.

I am currently accessing the parent directory of my file using Pathlib as follows:


When I print it, and this gives me the following output:

print('Parent: ', Path(__file__).parent)

The main-folder has a .env file which I want to access and for that I want to join the parent path with the .env. Right now, I did:

dotenv_path = os.path.join(Path(__file__).parent, ".env")

which works. But I would like to know, if there is a Pathlib alternate to os.path.join()?
Something like:

dotenv_path = pathlib_alternate_for_join(Path(__file__).parent, ".env")

Yes there is:

env_path = Path(__file__).parent / ".env"

/ is all you need. This will work in different OSs

You can use something like this:




Is the following definition of filepath closer in spirit to os.path.join?

import pathlib
filepath = pathlib.PurePath(main_dir, sub_dir, fname)

You can simply join Path objects and strings:

    import pathlib
    script_parent_path = pathlib.Path(__file__).parent
    my_dir = ".env"
    my_new_path = pathlib.Path(script_parent_path, my_dir)

That’s because:

Pathlib’s constructors accept 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 –

I think the easiest way to join paths is to use


See also definition of pathlib.Path(*pathsegments).

In the documentation the following statement and example is given for PurePath:

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

>>> PurePath('/etc', '/usr', 'lib64')


>>> PureWindowsPath('c:/Windows', 'd:bar')


Just for guys wondering how / works internally in pathlib.Path:

    # this is where the magic begins! (overload the "" operator)
    def __truediv__(self, key): 
            return self._make_child((key,))
        except TypeError:
            return NotImplemented

    def _make_child(self, args):
        drv, root, parts = self._parse_args(args)
        drv, root, parts = self._flavour.join_parsed_parts(
            self._drv, self._root, self._parts, drv, root, parts)
        return self._from_parsed_parts(drv, root, parts)

    def _from_parsed_parts(cls, drv, root, parts):
        self = object.__new__(cls)
        self._drv = drv
        self._root = root
        self._parts = parts
        return self  # finally return 'self', which is a Path object.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .