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 refer to our video player troubleshooting guide for assistance.

Accessing File Path Components (Recap)

00:00 So in this quick walkthrough, you got to see a couple of attributes on Path objects that are useful for accessing file path components. You learned about .parents that returns paths to all directories contained in the file path, and those are Path objects as well, so you can work with them in the same way as you do with other Path objects.

00:18 You can use .parent to get just the first parent directory, the ones directly above the resource that you’re pointing to. Then you can use .anchor to get a string representation of the root directory, but that only works if it’s an absolute path. Otherwise, you get an empty string.

00:37 And then you also have another attribute called .name that gives you the name of the file or of the directory that the path points to. Again, this is a string, so not a Path object.

00:47 And if you’re talking about actually files not folders, then you have two more things to do, something a little more specific. .stem gives you the filename before the dot, and .suffix returns the file extension. So, while on a file, .name gives you both the stem and the suffix, you can also be a little more precise and get only the stem and only the file extension with using .stem and .suffix. However, if the path points to a resource that doesn’t have a dot in the name, then .name and .stem return the same string, and .suffix is going to be an empty string.

01:23 That’s most often going to happen when you access a folder, but remember also a folder could have a . in the name and a file could have no extension, so it could happen for either resource.

01:35 So that was a quick overview of how you can access different file path components on pathlib.Path objects.

01:43 In the next lesson, you’ll finally get started with doing something with these files. You’ll start learning about common file system operations and how to handle them using Python’s pathlib module.

Become a Member to join the conversation.