Accessing File Path Components (Part 1)
So this file doesn’t actually exist, but it’s good enough for the purposes of showing you the attributes on this
Path object. Now you can get the parent paths that are involved in the path that points to this final resource here by using the
.parents attribute. Now, this is going to return something that won’t tell us much.
And then you can see that first you get
/Users/martin, which is this parent folder of
hello.txt. Then you get
/Users, which is this parent folder of the rest. And then finally, also the root directory. Now, these are not strings, actually.
There’s a shortcut for getting just the first parent that goes
f.parent, and that returns
Users/martin in that case. And it’s basically just a shortcut to
f.parents and then getting the first element. Except for the root folder, because this one doesn’t have any parents. So in that case,
.parent is going to return itself, and
.parents is going to be an empty iterable. So in that case, if you try to access the first element of
.parents , then you’d run into an
IndexError. If you’re curious, go ahead and try it out yourself.
Become a Member to join the conversation.