File Parts: Cheat Sheet

If you’ve ever said “I need to get the part of the file path that’s without the containing directory and without the suffix” and found it awkward, this cheat sheet is for you:


This is a companion discussion topic for the original entry at https://amir.rachum.com/blog/2018/06/29/file-parts/

This is such low quality content. Like come on, so much self promotion on this blog, you have a cartoon of your face bounce on every page load.

Also before spreading this lame infographic even further, you might want to check these out:

http://pubs.opengroup.org/onlinepubs/007908799/xcu/basename.html
http://pubs.opengroup.org/onlinepubs/007908799/xcu/dirname.html

I’m sorry you didn’t like this. I had this diagram in one of my notebooks and used it several times, so I thought it might be useful to others as well. Regarding self promotion - well, this is my personal blog, I write about programming as well as my personal life, so I feel this is natural.

If you feel this post is low on content (comparatively, it is), I suggest you take a look at some of my longer and more thorough posts, for example:

Unfortunately, you will have to suffer through the bounce of my cartoon on every page load - you have been warned.

I liked it. I’ve used a number of different methods for parsing filenames, this wasn’t one of them. Always good to have these kinds of things in your toolbox.

why does : call to parent, print also self …

p.parent
PurePosixPath(‘/bar/baz’)

While p.parent.name, is just & only the immediate parent

p.parent returns a new Path object (OS specific). Then, all the methods are relative to this new object. So p.parent.name returns the last part of the parent’s path.