Accessing File Path Components (Part 1)
00:00
In this lesson, you’ll get to know a couple of attributes on Path
objects and see what they return when you run them on a Path
object.
00:09
Let’s get started right away in IDLE. I will make my life a little easier and create a file path that doesn’t actually exist, but doesn’t matter, right? pathlib.Path
Then let’s say .home()
and
00:30
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.
00:53
It just says it’s a PosixPath.parents
, but this is an iterable, so you can loop over it and get all of the parents that are in there. You can write a for
loop.
01:04
You can say for p in f.parents:
and then print out p
.
01:12
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.
01:29
They’re Path
objects. You can inspect that by saying list(f.parents)
, and you can see that you get three Path
objects returned, so you can work with those also as Path
objects.
01:42
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.
02:18
Create a Path
object that points to your root folder and then try out .parent
and .parents
and see what they return.
Become a Member to join the conversation.