119

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

Path(__file__).parent

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

print('Parent: ', Path(__file__).parent)
#output
/home/user/EC/main-folder

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")
reinhardt
  • 1,873
  • 3
  • 9
  • 23
  • 2
    Does this answer your question? [How Do I Append a String To A Path in Python?](https://stackoverflow.com/questions/48190959/how-do-i-append-a-string-to-a-path-in-python) – Azat Ibrakov Apr 20 '20 at 11:43
  • 1
    https://docs.python.org/3/library/pathlib.html#operators – Alex Apr 20 '20 at 14:58
  • Also see this [comparison between os.path and pathlib in the docs](https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module) – djvg Mar 29 '22 at 10:03

6 Answers6

113

Yes there is:

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

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

quest
  • 3,576
  • 2
  • 16
  • 26
62

You can use something like this:

(Path(__file__).parent).joinpath('.env')

Documentation:

pathlib.Path.joinpath

Alex
  • 6,610
  • 3
  • 20
  • 38
some_programmer
  • 3,268
  • 4
  • 24
  • 59
11

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

import pathlib
main_dir = 'my_main_dir'
sub_dir = 'sub_dir'
fname = 'filename.tsv'
filepath = pathlib.PurePath(main_dir, sub_dir, fname)
Quetzalcoatl
  • 2,016
  • 4
  • 26
  • 36
  • 3
    I realize my suggestion may not directly address the context of the original question, but searching for "pathlib os.path.join alternative" returns this page as a top result :-) – Quetzalcoatl May 13 '21 at 06:33
8

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)
    print(my_new_path)

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 - https://docs.python.org/3/library/pathlib.html#pathlib.PurePath

1

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

    # this is where the magic begins! (overload the '/' operator)
    def __truediv__(self, key): 
        try:
            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)


    @classmethod
    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.
nealwp
  • 43
  • 7
starriet
  • 2,565
  • 22
  • 23
1

I think the easiest way to join paths is to use

Path(Path(__file__).parent,".env")

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')

PurePosixPath('/usr/lib64')

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

PureWindowsPath('d:bar')

Florian Feldhaus
  • 5,567
  • 2
  • 38
  • 46