I read that in pathlib
we can create a child path by using /
between two paths, where a comma would also work. However, I can't find out if there is a difference between the two cases. In the following example, the output is the same:
from pathlib import Path
p = Path('/hello', 'world')
s = Path(p, 'how', 'are', 'you')
ns = Path(p / 'how', 'are', 'you')
print(s)
print(ns)
But considering that pathlib
is heavily object-oriented, I guess there might be something different behind the scenes. Is there a difference between using /
in Path in contrast with a comma?
The whole point of using the /
operator between pathlib.Path
objects or a Path
object with a str
object is so you can avoid wrapping everything in calls to Path
.
>>> from pathlib import Path
>>> p = Path('/hello', 'world')
>>> p / 'how'
PosixPath('/hello/world/how')
>>> p / 'how' / 'are' / 'you'
PosixPath('/hello/world/how/are/you')
The distinction isn't between using "a comma" and a /
, it's between using /
and the constructor, Path
.
I suppose, /
is supposed to be similar to joinpath
:
>>> p.joinpath('how','are','you')
PosixPath('/hello/world/how/are/you')
But somewhere under the hood you are creating a new Path
instance, so Path
is called anyway.
Note, from the docs:
When several absolute paths are given, the last is taken as an anchor (mimicking os.path.join()’s behaviour):
So they both have this behavior as well:
>>> '/etc' / p / '/usr'
PosixPath('/usr')
>>> Path('/etc', p, '/usr')
PosixPath('/usr')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With