Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the parent directory's name only, not full path?

Tags:

python

path

I am trying to get the parent directory's name only. Meaning, only its last component, not the full path.

So for example for the path a/b/c/d/e I want to get d, and not a/b/c/d.

My current code:

import os

path = "C:/example/folder/file1.jpg"
directoryName = os.path.dirname(os.path.normpath(path)) 
print(directoryName)

This prints out C:/example/folder and I want to get just folder.


2 Answers

The simplest way to do this would be using pathlib. Using parent will get you the parent's full path, and name will give you just the last component:

>>> from pathlib import Path
>>> path = Path("/a/b/c/d/e")
>>> path.parent.name
'd'

For comparison, to do the same with os.path, you will need to get the basename of the dirname of your path. So that translates directly to:

import os

path = "C:/example/folder/file1.jpg"
print(os.path.basename(os.path.dirname(path)))

Which is the nicer version of:

os.path.split(os.path.split(path)[0])[1]

Where both give:

'folder'

As you can see, the pathlib approach is much clearer and readable. Because pathlib incorporates the OOP approach for representing paths, instead of strings, we get a clear chain of attributes/method calls.

path.parent.name

Is read in order as:

start from path -> take its parent -> take its name

Whereas in the os functions-accepting-strings approach you actually need to read from inside-out!

os.path.basename(os.path.dirname(path))

Is read in order as:

The name of the parent of the path

Which I'm sure you'll agree is much harder to read and understand (and this is just a simple-case example).


You could also use the str.split method together with os.sep:

>>> path = "C:\\example\\folder\\file1.jpg"
>>> path.split(os.sep)[-2]
'folder'

But as the docs state:

Note that knowing this [(the separator)] is not sufficient to be able to parse or concatenate pathnames — use os.path.split() and os.path.join() — but it is occasionally useful.

like image 146
Tomerikoo Avatar answered Sep 19 '25 21:09

Tomerikoo


Use pathlib.Path to get the .name of the .parent:

from pathlib import Path

p = Path("C:/example/folder/file1.jpg")
print(p.parent.name)  # folder

Compared to os.path, pathlib represents paths as a separate type instead of strings. It generally is shorter and more convenient to use.

like image 38
MisterMiyagi Avatar answered Sep 19 '25 23:09

MisterMiyagi