Accessing File Path Components (Part 2)
So I quickly cleared the screen so we have a little more space to see some other attributes. You’ve gotten to know
Now another one is
.anchor. So you can inspect the
.anchor attribute of a
Path object, and that’s going to return the root directory. In this case, however, it returns actually a string. So this is not a
00:22 That’s something to keep in mind. And it only works for absolute paths. If you have a relative path
and access the
then you get an empty string back. So mostly useful for absolute paths. What else? You can access the name of the resource that you’re pointing to. So
f.name gives me
Now because this is a filename, it has two additional parts that you can pick apart. You can get to the stem.
f.stem gives me
f.suffix gives the file extension,
'.txt'. If this wasn’t a file but a folder—so I can create a directory to show that as well.
and for a directory, everything works the same. You can use
.parent, you can use
.anchor, you can use
.name. Only then it becomes interesting for
.stem returns the same as
.name in this case because the directory name doesn’t have a
. in it, so there’s no place to split up between stem and suffix.
01:49 And conversely also, if you try to get the suffix of the folder, then you get back an empty string because there is no dot, so there’s just no part behind the dot.
01:59 And most often you’ll see this behavior for directories where the name of a directory usually doesn’t contain a dot, and files often contain a dot with a file extension, but there’s also files that don’t have a file extension, so you would see the same behavior there.
The bottom line is that
Path objects don’t really distinguish between a file and a folder, and there only these two different methods
.is_dir(), to figure out whether it’s a file or a directory.
Become a Member to join the conversation.