Reputation: 2664
I am playing around with Pathlib and trying to find out if there is an easy way to do the following - I have a group of paths from which I want to extract the first 4 parents, and join these 4 into a path.
Alternatively (if possible) I would like to join all parents up to the parent passed a given one, e.g., c://d1//d2//known//d4//...
here I want to extract up to //d4
, i.e., the parent just after the 'known' parent.
I know I could just loop over the parts and join up to the nth one, but I am wondering is there a way to do something like the following p.joinpath(p.parents[0:4])
, p.joinpath(p.parents[0: 'known_index'+1])
, or whatever is the most pythonic.
Update:
I managed to join up to the nth with tuple unpacking print(p.joinpath(*p.parts[0:5]))
, is there a preferred way and I have still not managed to achieve the goal of the alternative case mentioned above.
Update:
I found an option for the 'Alternative' case print(p.joinpath(*p.parts[0: p.parts.index('PCB_236_237_ARM')+2]))
I am now just looking for the most pythonic ways.
Upvotes: 3
Views: 795
Reputation: 9792
This looks pythonic enough to me:
p1 = pl.Path('c://d1//d2//known//d4//')
idx = p1.parts.index('known')
p2 = pl.Path(*p1.parts[:idx+1])
I use pl.Path(*segments)
to join the segments because the instance method p.joinpath()
appends the segments to the instance's p
own path.
Upvotes: 1