Accessing File Path Components (Recap)
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
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.
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
.suffix. However, if the path points to a resource that doesn’t have a dot in the name, then
.stem return the same string, and
.suffix is going to be an empty string.
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
Become a Member to join the conversation.