The Python Oracle

What is the difference between os.path.basename() and os.path.dirname()?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind

--

Chapters
00:00 What Is The Difference Between Os.Path.Basename() And Os.Path.Dirname()?
00:23 Accepted Answer Score 357
00:56 Answer 2 Score 13
01:40 Answer 3 Score 3
02:29 Thank you

--

Full question
https://stackoverflow.com/questions/2227...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 357


Both functions use the os.path.split(path) function to split the pathname path into a pair; (head, tail).

The os.path.dirname(path) function returns the head of the path.

E.g.: The dirname of '/foo/bar/item' is '/foo/bar'.

The os.path.basename(path) function returns the tail of the path.

E.g.: The basename of '/foo/bar/item' returns 'item'

From: http://docs.python.org/3/library/os.path.html#os.path.basename




ANSWER 2

Score 13


To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.




ANSWER 3

Score 3


Linux/macOS:

IMG:

Windows:

IMG:

Image sources: Linux/macOS; Windows.


Note that since Python 3.4, one can use pathlib.Path, as explained on https://miguendes.me:

Linux/macOS:

enter image description here

>>> from pathlib import Path

>>> path = Path('/home/miguel/projects/blog/config.tar.gz')

>>> path.drive
'/'

>>> path.root
'/'

>>> path.anchor
'/'

>>> path.parent
PosixPath('/home/miguel/projects/blog')

>>> path.name
'config.tar.gz'

>>> path.stem
'config.tar'

>>> path.suffix
'.gz'

>>> path.suffixes
['.tar', '.gz']

Windows:

enter image description here

>>> from pathlib import Path

>>> path = Path(r'C:/Users/Miguel/projects/blog/config.tar.gz')

>>> path.drive
'C:'

>>> path.root
'/'

>>> path.anchor
'C:/'

>>> path.parent
WindowsPath('C:/Users/Miguel/projects/blog')

>>> path.name
'config.tar.gz'

>>> path.stem
'config.tar'

>>> path.suffix
'.gz'

>>> path.suffixes
['.tar', '.gz']