How can I get just the last folder of a directory?

This seems like it should be simple but it seems few enough people are trying to do it that I really cant find anything on it. I am using a script using filepath to set a directory but I also need to get the name of the bottom-most folder in the path without the rest of it and I am having a bit of trouble.

For example, if a path is “one / two / three / four / test.blend” I only want the name of the last folder, or the containing folder, “four”

Assuming this is not one of those, simple concepts that are actually really hard moments, how might I be able to go about doing this?

how about:

path = "Path to initial folder"

to get a list of all childs that has the directory flag set.
-Note- the call still has tuning potential.

dirs = [ d for d in os.listdirs(path) if os.path.isdir(os.path.join(path, name)) ]

prints the last index of the list
print( dirs[-1] )

this would be one way to archive your goal

-edit-
just to round it up. by altering
...(path) if os.path...
to
...(path) if not os.path...
only containing files being handled

1 Like

@londo You sorely need to read up on pathlib.

To get the name of a file or directory’s parent it’s as simple at.

from pathlib import Path

path = Path("./foo/bar/blah.blend")
parent_name = path.parent.name # returns 'bar'

Though for whatever you’re doing you should probably just use path.parent as that will return a new Path object rather than a string.
https://docs.python.org/3/library/pathlib.html

1 Like

no need to…just was the first to come to my mind.
could have use any of the various options to get the desired result.
each of which have its pros and cons, discussed plenty of times in countless forums all over the www.
and based on personal experience, everyone’s formed their own set of what is the proper method.

but that’s not what the point is here.

I rather see answers to questions as push into the right direction as to see it as the holy grail.

Absolute nonsense.

Thank you so much. Ill have a chance to play with that this evening. It is basically acting as a display just to show which directory you are working in. It serves somewhat little functional purpose since the full path is needed by blender for most of the functional stuff. Im glad this is not some easier said than done thing because I basically just want this so you dont have to dig through a directory that doesnt fit in the panel to figure out where you are quickly.

That worked flawlessly. Thank you!