pathlib: Path.parts
is more flexible then Path.parents
what library to use
I would recommend using pathlib.Path
. Its the modern and object oriented way of handling paths in python.
Hence pathlib
is the first proposed library for File and Directory Access in the python docs: https://docs.python.org/3/library/filesys.html
how to handle paths
I want to point out the option to use the parts
method. Simply because its a bit more flexible.
With parents
, you start at the end of the path and navigate upwards. It is not really pratical to get up to the root of the path, as negative indexing is not supported.
With parts
on the other hand side, you simply split the path into a tuple and can operate on with with all list operations python offers.
>>> from pathlib import Path
>>> p = Path("/a/b/c/d/e.txt")
>>> p.parts
('/', 'a', 'b', 'c', 'd', 'e.txt')
So a small comparison of different usecases with parts
and parents
:
# get two levels up
>>> p.parents[1]
PosixPath('/a/b/c')
>>> Path(*p.parts[:-2])
PosixPath('/a/b/c')
# get second level after root
>>> p.parents[len(p.parents) - 3]
PosixPath('/a/b')
>>> Path(*p.parts[:3])
PosixPath('/a/b')
# unfortunately negative indexing is not supported for the parents method
>>> p.parents[-3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/user/.conda/envs/space221118/lib/python3.8/pathlib.py", line 620, in __getitem__
raise IndexError(idx)
IndexError: -3