Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Accessing File Path Components (Part 2)

00:00 So I quickly cleared the screen so we have a little more space to see some other attributes. You’ve gotten to know .parents and .parent.

00:08 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 Path object.

00:22 That’s something to keep in mind. And it only works for absolute paths. If you have a relative path

00:36 and access the .anchor attribute,

00:40 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 gives me 'hello.txt'.

00:56 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 'hello'.

01:06 And 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.

01:23 So this is a directory,

01:27 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 and .suffix.

01:38 So .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.

02:16 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_file() or .is_dir(), to figure out whether it’s a file or a directory.

Become a Member to join the conversation.