是否有一个 Pathlib 替代 os.path. join?

我目前正在使用 Pathlib访问我的文件的父目录,如下所示:

Path(__file__).parent

当我打印它时,它会给我以下输出:

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

main-folder有一个我想访问的 .env文件,为此我想将父路径与 .env连接起来。现在,我做到了:

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

但是我想知道,是否有一个 Pathlib替代 os.path.join()? 比如:

dotenv_path = pathlib_alternate_for_join(Path(__file__).parent, ".env")
56727 次浏览

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:

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

Documentation:

pathlib.Path.joinpath

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)

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

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.

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